jodd HttpRequest form set content-type invalid

326 Views Asked by At

HttpRequest set form content-type invalid

@Test
public void getImgCode() {
    Map<String, Object> param = new HashMap<>();
    param.put("userId", "11111");
    HttpRequest request = HttpRequest.post(baseUrl + "openapi/api/v2/getCode")
            .header("content-type","application/json;charset=utf-8")
            .form(param);

    System.out.println(request.contentType());

    HttpResponse response = request.send();
    System.out.println(response.bodyText());
}

but print content-type = application/x-www-form-urlencoded;charset=utf-8

if use httpQequest.query(param) so No problem,but query only Support String.

1

There are 1 best solutions below

0
On BEST ANSWER

Short answer: if you use form() you can not change the content type and the content length of your request. It is a special method for sending parameters encoded as multipart or url-encoded way in the body. This is simply the specification of HTTP :) By changing the content type your server will get the request that is not correct: it would expect json body, and not form parameters.

You can solve this issue in two ways:

  1. Either encode your input to JSON and set it as bodyText() and use application/json content-type; or
  2. don't try to change the content-type and use form.

It would be helpful if you can explain why do you need to change default value for content-type to JSON when no json is involved in this request?