In Java, using HttpPost (apache commons HttpClient) when sending JSON POST - should I encode the body url?

I am sending a RESTful JSON POST request using Apache HttpClient (third-party API)

  • Should I encode the JSON body url?

  • And if something in the content is already encoded in the URL (for example, I am sending HTML code that has some links with URL-encoded characters, for example, @ 22), should I expect the content to be on the other side, decode?

eg. if i do 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 to receive the same value on the receiving side, after receiving the key value "html"?

eg. on the receiving side

 //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 that I must follow to make sure that I send what is received "as is"?

+4
source share
2 answers

Here are two contexts you need to worry about:

  • Json
    You need to make sure that the JSON you create is valid JSON (duh). This means that all the syntaxes { } and [ ] are in the right place and make sure that the values โ€‹โ€‹of the fields that you insert into the JSON object are safely escaped (for example, escaping this HTML fragment in your question - quote characters must be escaped). BUT , because you are using the standard Java JSON library, you do not need to worry about it ... it will take care of all this for you.

  • HTTP
    The JSON string should then be inserted into the body of the HTTP request. No escaping is required here - just insert the original JSON string. HTTP, as a protocol, will accept anything inside the request / response bodies, including raw binary data.

In any case, it has been a long time, but I hope this helps.

+3
source

The Content-Type in your HTTP header should be application / json, so you should not encode the URL of the HTTP request.

URL encoding is designed to prevent users from using characters that are special when representing URLs (for example, '/').

You do not need to worry about links in decoded content unless you use the Content-Type in your http header, which assumes the server should decode the body, for example application / x-www-form- urlencoded

+1
source

Source: https://habr.com/ru/post/1415622/


All Articles