How to resolve "HTTP Error 411. The request must be fragmented or have a content length." in java

I am using HttpConnect and trying to get some token from the server. But whenever I try to get an answer, it always says that you did not ask or a problem with the length of the content, even I tried to set the length of the content in different ways.

conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod(method); conn.setRequestProperty("X-DocuSign-Authentication", httpAuthHeader); conn.setRequestProperty("Accept", "application/json"); if (method.equalsIgnoreCase("POST")) { conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", Integer.toString(body.length())); conn.setDoOutput(true); } status = conn.getResponseCode(); // triggers the request if (status != 200) { //// 200 = OK errorParse(conn, status); return; } InputStream is = conn.getInputStream(); 
+6
source share
2 answers

HttpConnect from HttpConnect to HttpClient worked for me. So I walked away from HttpURLConnection and created an http HttpClient object and called the execute methods to get data from the server.

Below is the code that makes an http request using HttpClient rather HttpURLConnection

 try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(authUrl); String json = ""; JSONObject jsonObject = new JSONObject(); jsonObject.accumulate("phone", "phone"); json = jsonObject.toString(); StringEntity se = new StringEntity(json); httpPost.setEntity(se); httpPost.addHeader("Accept", "application/json"); httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded"); HttpResponse httpResponse = httpclient.execute(httpPost); // 9. receive response as inputStream inputStream = httpResponse.getEntity().getContent(); String response = getResponseBody(inputStream); System.out.println(response); } catch (ClientProtocolException e) { System.out.println("ClientProtocolException : " + e.getLocalizedMessage()); } catch (IOException e) { System.out.println("IOException:" + e.getLocalizedMessage()); } catch (Exception e) { System.out.println("Exception:" + e.getLocalizedMessage()); } 
0
source

You set the length of the content, but do not send the request body.

Do not set the length of the content. Java does it for you.

NB setDoOutput(true) sets the POST method.

0
source

All Articles