Home > Enterprise >  How to calculate Content-Length of a request body of a Http Post Request
How to calculate Content-Length of a request body of a Http Post Request

Time:10-09

I am trying to calculate the Content-Length of the request body of a http post request but I keep getting error that indicated wrong Content-Length. Request body looks like following:

Map<String, String> body = {
  'grant_type': 'authorization_code',
  'client_id': 'clientid',
  'code': authCode,
  'redirect_uri': 'http://localhost:8080/login/callback',
  'code_verifier':
      'codeverifier',
};

I tried couple solutions like concatenating content of the body into one string such as following and then convert it into byte array and send the length of it but it didn't work.

String bodyStr = "grant_type:authorization_code"  
    "client_id:clientid"  
    "code:{$authCode}"  
    "redirect_uri:http://localhost:8080/login/callback"  
    "code_verifier:codeverifier";
    List<int> bytes = utf8.encode(bodyStr);

The post request body is x-www-form-urlencoded format and content length has to be calculated correctly. Any help is appreciated, thanks.

CodePudding user response:

You don't need to make a list of integer...

String bodyStr = "...";
byte[] bytes = bodyStr.getBytes(Charset.forName("UTF-8"));
int len = bytes.length;
response.setContentLength(len);
response.getOutputStream().write(bytes);

This example is using the HttpServletResponse object from a HttpServlet. Not sure if that's what you need.

I have used this a fair amount, it works well.

CodePudding user response:

I encapsulated it myself. Generally, I don't need to calculate it. Unless it's a special occasion. Okhttp3 is recommended

  • Related