response with appropriate mime type requested with accept - laravel

Say I have a route:
Route::get('list',...);
If I call that route with Accept: text/html it should return a view with all the blade hoopla.
If I call that route with Accept: application/json it should return json, Accept: application/xml it will return xml.
And so on...
How do I realise that with Laravel 5.1?

You can handle Accept header using these methods of the Request class:
bool accepts(string|array $contentTypes)
If you just care about Json and HTML there is
bool acceptsJson() / bool wantsJson()
bool acceptsHtml()

Related

How to get JSON from request Laravel?

I use this method:
public function store(CreateEvent $request)
{
dd($request->json()->all());
}
My requests is:
{"name":"etegjgjghjghj","date":"2019-03-08"}
Headers:
Accept: application/json, text/plain, */*
Content-Type: application/json
Origin: http://localhost:4200
As response I get blank page in Chrome network without response data.
I tried this:
public function store(CreateEvent $request){ dd('test'); }
try this:
public function store(CreateEvent $request)
{
return response()->json($request->all());
}
If the request has header 'Content-Type: application/json' and it's a valid JSON, then laravel will convert it automatically. You don’t need to do any extra job.
But you have to make sure the JSON is correct. Because JSON must contain double quoted strings not single (if has any)
Next thing, your form validation probably shooting 422 request which by default redirects back to previous page. you can try dd in the form request class

How to create a Post request in Fiddler

trying to send a Fiddler Post request to my C# API as follows (this is my dev environment using VS2012). However, my request object is null in C#. In the parsed tab of the composer tab. My post URL: http://localhost:33218/api/drm
User-Agent: Fiddler/4.4.9.2 (.NET 4.0.30319.34209; WinNT 6.1.7601 SP1; en-US; 4xAMD64)
Pragma: no-cache
Accept-Language: en-US
Host: localhost:33218
Accept-Encoding: gzip, deflate
Connection: Close
Content-Length: 80
Request Body:
&sid=f7f026d60bb8b51&riskMeasureName=RMTest
And here's the C# API method:
// POST api/drm
public HttpResponseMessage Post([FromBody]JObject drmObject)
{
string sid = drmObject.GetValue("sid").ToString();
string riskMeasCategory = drmObject.GetValue("riskMeasureName").ToString();
string response = DynAggrClientAPI.insertDRMCategory(sid, riskMeasCategory);
var httpResp = Request.CreateResponse(HttpStatusCode.OK);
httpResp.Content = new StringContent(response, Encoding.UTF8, "application/json");
return httpResp;
}
I can debug in my C# Post() method, but the drmObject is null.
Your advice is appreciated.
You're not sending a content-type, so MVC has no way to tell how to interpret the data.
Your data seems to resemble a form POST, so add the header:
Content-Type: application/x-www-form-urlencoded

$stateProvider requests template in templateURL with accept header as application/json which must be text/html

when we are actually requesting for a template url . The accept header is always application/json instead of text/html
I am currently Using nancy for generating both template and api request based on the content request type on accept headers .
Something like this
private dynamic Index(dynamic parameters)
{
Students = NancyContext.Set<Student>().ToList();
Negotiate.WithView("Index").WithModel(Students);
}
which basically when requested with application/json returns json . And when requested with text/html then it returns the template with model . But since its requesting the template with application/json . Its only returning json for the api request and not the template . Any workaround for to change the accept header to text/html instead of application/json for template url ?
IT was feature which was supposed to be integrated . So it has been integrated into
#1287

REST method's won't PUT or POST to the server

I'm trying to get some REST methods working in my Spring app but seem to be running into little success. I'm obviously missing something but I can't tell for the life of me what it would be. Here is my controller:
#Controller
public class IndexController {
static Logger log = Logger.getLogger(IndexController.class);
#Autowired
private ProvisionService provisionService;
#RequestMapping(value="/home/data", method=RequestMethod.GET,
headers="Accept=application/json")
public #ResponseBody List<Provision> getData() {
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String username = null;
if(principal instanceof UserDetails)
username = ((UserDetails)principal).getUsername();
return provisionService.getAllByUser(username);
}
//JSON put request - doesn't work currently
#RequestMapping(value="/home/data", method=RequestMethod.PUT,
headers="Content-Type=application/json")
#ResponseStatus(HttpStatus.NO_CONTENT)
public void updateProvisions(#RequestBody List<Provision> provisions) {
log.info("Provisions: " + provisions.toString());
}
#RequestMapping(value={"/","/home"}, method=RequestMethod.GET)
public void showIndex() {}
}
Here is the main part of JSP that utilizes it:
<sf:form id="homeForm" method="put" action="${homeData_url}"></sf:form>
The form is submitted through Javascript when the user clicks on a button. Anyway, things work fine for the GET. I get Json returned with my List of objects, no problems. I then display that using Dojo and so far so good. However, when I try to return the Json with this form I'm getting a 405 - Request method 'POST' not supported error. As you can see I've got the method handler in my Controller so I'm really not sure what I'm doing wrong. I've taken those handler's out of the Spring in Action 3 book and it also resembles what some Spring docs and stuff say to do, but obviously I'm missing a key component. Anyone have any thoughts?
I do have the HiddenHttpMethodFilter mapped in my web.xml which is why I'm using the Spring form tag.
Anyway, any thoughts or help are appreciated. Thank you.
------------------UPDATE------------------
Here are the headers after I click on the button and get the 405 error, if it helps:
http://localhost:8080/NFI/home
POST /NFI/home HTTP/1.1
Host: localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:7.0.1) Gecko/20100101 Firefox/7.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
DNT: 1
Connection: keep-alive
Referer: http://localhost:8080/NFI/home
Cookie: JSESSIONID=584AC21ADE4F214904B9E7E2370363EF
Content-Type: application/x-www-form-urlencoded
Content-Length: 11
HTTP/1.1 405 Method Not Allowed
Server: Apache-Coyote/1.1
Allow: GET, PUT
Content-Type: text/html;charset=utf-8
Content-Length: 1085
Date: Fri, 21 Oct 2011 15:39:26 GMT
Submitting a Form is done using POST. You get a "POST" not supported error.
Above, I see you are using a RequestMethod.PUT in your source code. There's no mention of POST at all.
Add you need to add a parameter _method with value PUT to your request. Not to the json content!
So in the first step I would change requested URL to /home/data?_method=PUT.
If this work you can search for an way how to add the _method parameter to the request content without disturbing the Json data.
You updated your question with the headers, could you also put the entire request out there (actual dumped values) to see the _method parameter(s) being sent?
Also, while I guess the headers=""-rules are valid they shouldn't be needed. You have a json converter bean that will do marshall and unmarshall based on content-type and accept headers, if no valid converter is found Spring will return an error.
The only reason to include it in the #RequestMapping would be if you had a method that actually did something else if you called it with xml instead of json and that sounds like a bad design.
Remove those header-rules and try again, make it as simple as possible and gradually add logic.

Problem with Spring 3 + JSON : HTTP status 406?

I'm trying to get a list of Cities by sending the State name through Ajax in my SpringMVC 3.0 project.
For the purpose, I've used the following call (using jQuery) in my JSP:
<script type="text/javascript">
function getCities() {
jq(function() {
jq.post("getCities.html",
{ stateSelect: jq("#stateSelect").val()},
function(data){
jq("#cities").replaceWith('<span id="cities">Testing</span>');
});
});
}
</script>
And here's my Controller code:
#RequestMapping(value = "/getCities", method = RequestMethod.POST)
public #ResponseBody List<StateNames> getCities(#RequestParam(value="stateSelect", required=true) String stateName,
Model model) {
// Delegate to service to do the actual adding
List<StateNames> listStates = myService.listCityNames(stateName);
// #ResponseBody will automatically convert the returned value into JSON format
// You must have Jackson in your classpath
return listStates;
}
But I get HTTP 406 error stating the following when i run it:
406 Not Acceptable
The requested resource is only capable of generating content not acceptable according to the Accept headers sent in the request.
I've used Jackson in my Maven dependencies & have defined in my context file.
I've googled extensively & I guess the problem is #ResponseBody is not automatically converting my List to appropriate JSON object.
My Firebug says:
Response Headers
Server Apache-Coyote/1.1
Content-Type text/html;charset=utf-8
Content-Length 1070
Date Sat, 12 Feb 2011 13:09:44 GMT
Request Headers
Host localhost:8080
User-Agent Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13
Accept */*
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip,deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive 115
Connection keep-alive
Content-Type application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With XMLHttpRequest
Referer http://localhost:8080/MyApplication/
Content-Length 17
Cookie JSESSIONID=640868A479C40792F8AB3DE118AF12E0
Pragma no-cache
Cache-Control no-cache
Please guide me. What am i doing wrong?? HELP!!
As Peter had written in his comment, the cause of the problem is inability of Spring to load Jackson. It is not loaded by dependencies by default. After I've added the dependency
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>1.9.2</version>
</dependency>
the JSON was returned after typing the address in the browser, without any tricks with Accept headers (as it is supposed to do).
Tested on Tomcat 7.0.
You have incorrect response content type it supposed to be application/json.
You need to add jackson to your /lib directory.
and you should have
<mvc:annotation-driven />
In your serlvet-name.xml file.
In addition I recommend you to map your request as get and try to browse it with Google Chrome,to see if it returns correct result. It has very good json representation.
The problem is not on server side, but on the client one.
Take a look at the error message carefully: The requested resource (generated by server side) is only capable of generating content (JSON) not acceptable (by the client!) according to the Accept headers sent in the request.
Examine your request headers:
Accept */*
Try this way:
function getCities() {
jq(function() {
jq.post(
"getCities.html", // URL to post to
{ stateSelect: jq("#stateSelect").val() }, // Your data
function(data) { // Success callback
jq("#cities").replaceWith('<span id="cities">Testing</span>');
},
"json" // Data type you are expecting from server
);
});
}
This will change your Accept header to the following (as of jQuery 1.5):
Accept: application/json, text/javascript, */*; q=0.01
This will explicitly tell the server side that you are expecting JSON.
Using jQuery , you can set contentType to desired one (application/json; charset=UTF-8' here) and set same header at server side.
REMEMBER TO CLEAR CACHE WHILE TESTING.
I too had a similar problem while using the Apache HTTPClient to call few services. The problem is the client and not the server. I used a HTTPRequester with header accepting application/json and it worked fine.

Resources