问题
I'm sending a RESTful JSON POST request using Apache HttpClient (to a 3rd party API)
Should I URL encode the JSON body?
And if something in the content is already URL encoded (e.g. I send HTML that has some links with URL encoded chars, e.g. @22) should I expect to get the content as is on the other side without it being decoded?
E.g. if i'm doing something like this
String html = "<a href='http://example.com?charOfTheDay=%22'>click me</a>";
// Build the JSON object
JSONObject jsonObj = new JSONObject();
jsonObj.put("html", html);
jsonObj.put("otherKey",otherValue);
//...
// Create the POST object and add the parameters
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);
Should I expect getting the same value on the receiving end, after getting the value of the "html" key?
e.g. on the receiving end
//after parsing the request string to a JSON object
String html = inputJsonObject.get("html")
// should return "<a href='http://example.com?charOfTheDay=%22'>click me</a>"
Are there any other steps I need to do to make sure what I send is what is received "as is"?
回答1:
There's sort of two contexts you have to worry about here:
JSON
You have to make sure that the JSON you generate is valid JSON (duh). This means making sure that all the{ }and[ ]syntax is in the right place and making sure that the field values you are inserting into the JSON object are safely escaped (like escaping that HTML snippet in your question --some of the quote characters would need to be escaped). BUT because you're using a standard JSON Java library, you don't have to worry about this...it will take care of all this for you.HTTP
The JSON string then has to be inserted into the HTTP request body. No escaping needs to be done here--just insert the raw JSON string. HTTP, as a protocol, will accept anything inside the request/response bodies, including raw binary data.
Anyway that was kind of long, but I hope it helped.
回答2:
The Content-Type in your http header should be application/json, so you oughtn't URL encode the body of the http request.
URL encoding is meant to prevent users from using characters that are special in representing URLs (such as '/').
You don't have to worry about links in the content being decoded either, unless you use a Content-Type in your http header that suggests that the server should decode the body, such as application/x-www-form-urlencoded
来源:https://stackoverflow.com/questions/10854115/in-java-using-httppost-apache-commons-httpclient-when-sending-json-post-sho