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

前端 未结 2 1700
眼角桃花
眼角桃花 2021-01-03 07:46

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 i

相关标签:
2条回答
  • 2021-01-03 08:37

    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

    0 讨论(0)
  • 2021-01-03 08:38

    There's sort of two contexts you have to worry about here:

    1. 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.

    2. 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.

    0 讨论(0)
提交回复
热议问题