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

前端 未结 2 1726
眼角桃花
眼角桃花 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: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.

提交回复
热议问题