如何解决“HTTP错误411.请求必须分块或具有内容长度”。在java中

时间:2016-03-23 22:23:10

标签: java http httpurlconnection

我正在使用HttpConnect并尝试从服务器获取一些令牌。但每当我尝试获得响应时,它总是说你没有设置内容长度或问题,即使我试图以多种不同的方式设置内容长度

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();

2 个答案:

答案 0 :(得分:0)

您正在设置内容长度,但从不发送请求正文。

不要设置内容长度。 Java为你做到了。

NB setDoOutput(true)将方法设置为POST。

答案 1 :(得分:0)

离开HttpConnectHttpClient为我工作。所以我离开HttpURLConnection并创建了一个http HttpClient对象并调用execute方法从服务器获取数据。

以下是使用HttpClient而非HttpURLConnection

发出http请求的代码
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());
}