I'm in need of some desperate help. I've been at this for 4 hours, and I'm getting pretty worn out. :/ Here's my situation:
I have a Javascript application that is making a POST request (using jQuery $.post) to an external site. On the external site I have Apache Camel running with Jetty to expose it to the web. The web services I wrote in Camel expect JSON data for all of the requests. For instance, one request needs an id, so I send it {"id": 10}.
Here's my issue: it doesn't work from Javascript. I have a few different tools that will send post requests for me (like the Poster extension for browsers). If I use Poster and set the body to {"id": 10}, it works just fine. I get that exact string in the service.
But, if I post from Javascript, I get something different. Posting the JSON object will give me the string "id=10" on my service side. (It's OK for this scenario, but I will need actual JSON objects eventually.) If I stringify the JSON object, I get the JSON string, only all of the characters are escaped. (Ex. "%7Bid%33...").
I swear I've tried every method possible for posting the data, but I either get the weird already parsed JSON, or the escaped string (or nothing at all). Is there some way I can have Javascript NOT parse the JSON object and just send it (like my posting tool does)? If not, is there a safe, efficient way to un-escape the JSON string that I get?
I really appreciate any help.
I feel like we need a little bit more information, but take a look at this javascript plugin. It may be your solution: https://github.com/flowersinthesand/jquery-stringifyJSON
Try using jQuery.ajax and setting processData to false (defaults to true):
$.ajax({
url: '/where/to/post',
type: 'POST',
data: {"id": 10},
processData: false
});
Usually, jQuery converts anything in data to query string format like id=10. The processData flag tells jQuery to interpret it literally as a json hashmap.
Posting the JSON object will give me the string "id=10" on my service side.
Javascript does not do your this conversion, so your server does it.
It is likely that your server reacts differently based on the content-type of your POST e.g. application/json vs text/plain or text/html, a common feature of REST based services.
The answers here gave me a few hints, but ultimately, it was a lot of tweaking before it would work correctly. I had to do 3 things:
Add processData: false.
Turn the JSON object into a JSON string. The request wouldn't fire if I left it as an object (even if I changed contentType to application/json).
Change the contentType to text/plain. This sent it as a raw string.
And that's what did the trick. I now get the JSON string I want on the server side.
Related
I started API testing recently and facing different content-types each time, and i wan to know specific in what case we use ContentType.URLENC, I kinda sure we use it with x-www-form-urlencoded, but still confusing and we use it with usually POST request ?
Firstly, when you want to send infomation to server, you need to tell the server how you structure your message in BODY part. Below is some basic ContentType:
Using key-value with&: you can choose x-www-form-urlencoded.Since there are some special characters in your message, then these need to be encoded. That's why urlencoded.
Eg: name=abc&age=20
Json type: choose application/json .
Eg:
{
"name": "abc",
"age": 20
}
Want to send a file: choose form-data
Secondly, BODY part usually goes with POST and PUT request.
I have tried the following line in my ajax call as it was suggested all over internet:
contentType: "application/json; charset=ISO-8859-1"
but it did not change anything. Whenever I make a call from ajax with a string parameter which has an accent for example società , at my controller(I'm using Java, spring framework), i receive it as SocietÃ. I have tried first UTF-8 which is the default (as far as I know) but nothing. Here is my full function:
function foo(customer, society) {
$.ajax({
url: 'notMappedAcoStaffing.do',
type: "GET",
contentType: "application/json; charset=ISO-8859-1",
data: { customer: customer, society: society},
success: function(data) { $('#content').html(data); },
error: function(error) { alert("error" + error); }
});
}
And I take the values on my backend as
#RequestMapping(method = RequestMethod.GET)
public ModelAndView fooController(#RequestParam("customer") final String customerParam, #RequestParam(value="society",required=false) Integer societyParam) {...}
Is there a way to resolve this issue?
Thanks for your help in advance.
UPDATE: I have still no idea why I receive it distorted as parameter at my controller. But however when I convert it as follows: How do I convert between ISO-8859-1 and UTF-8 in Java? ,it comes out all good. Seeing that it works, I tried it again to set UTF-8 in my ajax call but no success... It resolved my issue but honestly I do not like this way. Please share with me if you have a better solution maybe on the ajax call side. Thanks
Part of your problem is that you're using HTTP GET, which basically means that your data will be embedded in the URL itself, in the query string ( http://example.org/?customer=foo&society=bar ). This can lead to problems when using special characters.
Especially, the contentType property concerns the body of the request which you do not have at all so currently it has little impact.
Consider sending the data with HTTP POST (and remove your custom contentType) which gives you more power over the encoding of your data - which is then sent in the request body instead of the URL. It might solve your problem outright, or you might need to configure your server to use the same encoding as the client
- I suggest UTF-8 for both parties.
Sorry if this is a duplicate question but google isn't smart enough to understand me or I'm too dumb to express my question simple enough for it to understand.
I don't know if this is my problem but I'm 90% sure this is it.
I'd like to know how to represent a Unix path within a GET request so that my web service doesn't return a 404. I think it's because one of my JSON fields in the query is a Unix path and because of the slashes, the webservice thinks it's part of the URL and not a part of my query.
For example, I'm using a RESTClient that's an add-on to Mozilla to test my web service. For the POST request, I enter as the url
http://mytestserver:8080/mydir/
and in the body, I put in my JSON object
{"filename":"obit.jpg", "Path":"test/2/1"}
This method works fine. I get a status code 200 and a return JSON object with the expected output.
When I use the same string for a GET request, I get a status code 404 and no return JSON object. I put as the url in the RESTClient
http://mytestserver:8080/mydir/{"filename":"obit.jpg", "Path":"test/2/1"}
and I get a status code 404 and the response body just says 404 - Not found
To further test my theory, I entered the following url in a GET request, removing the /2/1 from the path, which works.
http://mytestserver:8080/mydir/{"filename":"obit.jpg", "Path":"test"}
I've tried encapsulating the whole JSON string in quotes but that didn't work either so I've run out of things to try.
Thanks in advance for any help you can give me. If I need to show some code, please let me know, although, I don't think it's a code problem, I think it's a representation problem. Thanks.
Found out that JSON objects are usually sent via POST, not GET. Since I appended it to the URL via GET, it gave me problems. Per How to send a GET request with a "/" in the query
I recently moved over to Java and am attempting to write some REST tests against the netflix REST service.
I'm having an issue in that my response using rest assured either wants to send a gzip encoded response or "InputStream", neither of which provide the actual XML text in the content of the response. I discovered the "Accept-Encoding" header yet making that blank doesn't seem to be the solution. With .Net I never had to mess with this and I can't seem to find the proper means of returning a human readable response.
My code:
RestAssured.baseURI = "http://api-public.netflix.com";
RestAssured.port = 80;
Response myResponse = given().header("Accept-Encoding", "").given().auth().oauth(consumerKey, consumerSecret, accessToken, secretToken).param("term", "star wars").get("/catalog/titles/autocomplete");
My response object has a "content" value with nothing but references to buffers, wrapped streams etc. Trying to get a ToString() of the response doesn't work. None of the examples I've seen seem to work in my case.
Any suggestions on what I'm doing wrong here?
This has worked for me:
given().config(RestAssured.config().decoderConfig(DecoderConfig.decoderConfig().noContentDecoders())).get(url)
I guess in Java land everything is returned as an input stream. Using a stream reader grabbed me the data I needed.
Until its version 1.9.0, Rest-assured has been providing by default in the requests the header "Accept-Encoding:gzip,deflate" with no way of changing it.
See
https://code.google.com/p/rest-assured/issues/detail?id=154
It works for me:
String responseJson = get("/languages/").asString();
All,
I'm trying to find out, unambiguously, what method (GET or POST) Flash/AS2 uses with XML.sendAndLoad.
Here's what the help/docs (http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00002340.html) say about the function
Encodes the specified XML object into
an XML document, sends it to the
specified URL using the POST method,
downloads the server's response, and
loads it into the resultXMLobject
specified in the parameters.
However, I'm using this method to send XML data to a Java Servlet developed and maintained by another team of developers. And they're seeing log entries that look like this:
GET /portal/delegate/[someService]?svc=setPayCheckInfo&XMLStr=[an encoded version of the XML I send]
After a Google search to figure out why the POST shows up as a GET in their log, I found this Adobe technote (http://kb2.adobe.com/cps/159/tn_15908.html). Here's what it says:
When loadVariables or getURL actions are
used to send data to Java servlets it
can appear that the data is being sent
using a GET request, when the POST
method was specified in the Flash
movie.
This happens because Flash sends the
data in a GET/POST hybrid format. If
the data were being sent using a GET
request, the variables would appear in
a query string appended to the end of
the URL. Flash uses a GET server
request, but the Name/Value pairs
containing the variables are sent in a
second transmission using POST.
Although this causes the servlet to
trigger the doGet() method, the
variables are still available in the
server request.
I don't really understand that. What is a "GET/POST hybrid format"?
Why does the method Flash uses (POST or GET) depend on whether the data is sent to a Java servlet or elsewhere (e.g., a PHP page?)
Can anyone make sense of this? Many thanks in advance!
Cheers,
Matt
Have you try doing something like that :
var sendVar=new LoadVars();
var xml=new XML("<r>test</r>");
sendVar.xml=xml;
sendVar.svc="setPayCheckInfo";
var receiveXML=new XML();
function onLoad(success) {
if (success) {
trace("receive:"+receiveXML);
} else {
trace('error');
}
}
receiveXML.onLoad=onLoad;
sendVar.sendAndLoad("http://mywebserver", receiveXML, "POST");
The hybrid format is just a term Macromedia invented to paint over its misuse of HTTP.
HTTP is very vague on what you can do with GET and POST. But the convention is that no message body is used in GET. Adobe violates this convention by sending parameters in the message body.
Flash sends the same request regardless of the server. You have problem in Servlet because most implementation (like Tomcat) ignores message body for GET. PHP doesn't care the verb and it processes the message body for GET too.