how to add custom content-type as json in spring mvc? - spring

I have a client application which is dated and is sending the request headeer as Content-Type: json instead of Content-Type: application/json.
There is no way (in the near future) the client application can be changed.
I am implementing the services using Spring and I almost got the endpoint working but only when content-Type is application/json. if "json" is set s content-type, I get 415 unsupported MediaType error, which makes sense.
How can I work around this problem, a hack for a short term fix would be ideal
This works but requires the client to send the header as "application/json"
#RequestMapping(value="person", method = RequestMethod.POST, consumes="application/json")
#ResponseBody
public List<PersonProfile> getProfiles (#RequestBody Wrapper wrapper) {
This fails during container start-up
#RequestMapping(value="person", method = RequestMethod.POST, consumes="json")
#ResponseBody
public List<PersonProfile> getProfiles (#RequestBody Wrapper wrapper) {

415 unsupported MediaType error.
I don`t know your ajax code.
But, you read in jquery document. maybe solve
contentType
contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')
Type: Boolean or String
When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). As of jQuery 1.6 you can pass false to tell jQuery to not set any content type header. Note: The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding. Note: For cross-domain requests, setting the content type to anything other than application/x-www-form-urlencoded, multipart/form-data, or text/plain will trigger the browser to send a preflight OPTIONS request to the server.
dataType
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:
"xml": Returns a XML document that can be processed via jQuery.
"html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
"script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, =[TIMESTAMP], to the URL unless the cache option is set to true. Note: This will turn POSTs into GETs for remote-domain requests.
"json": Evaluates the response as JSON and returns a JavaScript object. Cross-domain "json" requests are converted to "jsonp" unless the request includes jsonp: false in its request options. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.)
"jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string parameter, "=[TIMESTAMP]", to the URL unless the cache option is set to true.
"text": A plain text string.
multiple, space-separated values: As of jQuery 1.5, jQuery can convert a dataType from what it received in the Content-Type header to what you require. For example, if you want a text response to be treated as XML, use "text xml" for the dataType. You can also make a JSONP request, have it received as text, and interpreted by jQuery as XML: "jsonp text xml". Similarly, a shorthand string such as "jsonp xml" will first attempt to convert from jsonp to xml, and, failing that, convert from jsonp to text, and then from text to xml.
And you need to search by consumes and produces.
You wrong using consumes..

Related

Hapijs avoid json validation when Content-type: application/json is present

I'm trying to receive a json payload on a hapijs server, that json may not be valid, since is some custom format that i need to manually proxy the request to an elasticsearch cluster, cannot use the proxy option for hapijs because i need to do multiple requests to different clusters, for that i use nodejs http library.
Elasticsearch doesn't receive a valid json when doing bulk actions, it receives new lines instead of commas, to separate json objects:
{"index":[".kibana-devnull"],"ignore_unavailable":true}
{"size":500,"sort":[]}
Hapijs tries to validate the json payload when it gets application/json header in the request and it responds "Invalid request payload JSON format", as i cannot remove that header i need to look for another method to allow that invalid json in the route, even if the header is present.
I would look at the docs, in particular http://hapijs.com/api#route-configuration. If you set payload.output.parse to false you will receive the raw buffer inside handler which can then be parsed by yourself as opposed to by the framework.

temporarily change $http.defaults.transformResponse

How can I customize $http in angularjs such that it will accept strings as its response in a $http.post call? Right now, when I do a $http.post call, my response is in string but angularjs by default uses JSON therefore I get an error. Right now I have something along the lines of
function getResponseURL(response) {
//this will convert the response to string
return response;
}
$http.defaults.transformResponse = [];
$http.defaults.transformResponse.unshift(getResponseURL);
However if I use the code above, any $http.post calls after that call uses string. I want it to use the original default JSON format. How can I go about into just temporarily changing the response to string for this one call but the rest stay as JSON type as a response?
Why not only register that transform for ONLY that request?
Angular js $http docs
If you wish
override the request/response transformations only for a single
request then provide transformRequest and/or transformResponse
properties on the configuration object passed into $http.

variables post in koa framework

hi where is the data in post call in koa without co-body or bodyparse or why this error
Error: invalid JSON, only supports object and array
at parse (d:\Proyectos\koaJsTest\node_modules\co-body\lib\json.js:56:13)
co-body performs this regex unless the "strict" option is set to false:
/^[\x20\x09\x0a\x0d]*(\[|\{)/
Perhaps your json is making it to co-body as a URL-encoded string?
Its either going to be the format of the JSON that you are uploading if you are setting the Content-Type to application/json.
Otherwise, may be using the wrong Content-Type. For example if you were uploading files where the Content-Type should be multipart/form-data but you accidentally set the Content-Type to application/json when it should you would see this error.
This has tripped me up in the past.

Using $.ajaxSetup() to append a data object to AJAX calls in Spine

I am using the $.ajaxSetup() function to append some additional params to each of my AJAX calls in Spine. However it isn't working as i'd expect it to.
If i call $ajaxSetup() as follows, my GET requests work fine, but my params are overidden with any POST requests and are not included in the form data as id expect:
$.ajaxSetup
data: "user_email=foo#bar.com&user_token=foobar"
As a result i tried changing my data string to an object to see if that made any difference:
settings =
data:
user_email:'foo#bar.com'
user_token:'foobar'
$.ajaxSetup settings
However that causes my URL's in my requests to appear malformed, like so:
http://dev.myapp.com:5000/api/v1/posts?[object%20Object]
I've tried recreating this in JSFiddle (my fiddle) to test that i wasn't going mad and it seems that my approach works as i'd expect over there. For GET requests, a string of my data object is appended to the end of my URL and with POST requests the data object is appended to the form data sent with the request.
So what am i doing wrong? Is this a bug in Spine or something else?
jQuery Version: 2.0.3
It looks like the problem is that spine sets data as a string:
type: 'POST'
contentType: 'application/json'
data: #record.toJSON()
(from the spine source)
You can use ajaxPrefilter to fix up requests before they are sent. Since the data is a JSON string you have a couple of options:
add your parameters to the JSON (by decoding it, using $.extend, then encoding it again)
add your parameters as custom HTTP headers instead of POST parameters
add the parameters to the URL, even on POST requests

Can I make my OData request in JSON format?

I know OData supports responding in JSON format when it's given the appropriate Accept header:
Accept: application/json
Some articles say you'll need to specify odata verbosity otherwise you'll get the default xml format, but I have not seen this to be actually true. But let me mention it anyway:
Accept: application/json;odata=verbose
But (how) can I make my request using JSON instead of a querystring?
OData doesn't provide a way to specify the query in a request body, it only supports the query in the URL. So the answer is that there's no way to do that in JSON. Note that it applies to GET requests. Modification requests (POST/PUT/...) do accept JSON as the payload (typically representing an entity for example), in which case simply specify the content type of the request in its Content-Type header.
There are java script libraries which let you build the query string using more structured code (as compared to just strings). For example the datajs http://datajs.codeplex.com/.

Resources