Mat*_*uis 3 java rest apache-httpclient-4.x
我试图使用Apache Httpclient将一些JSON发布到休息服务.但是,我收到此错误:
Exception in thread "main" org.apache.http.ProtocolException: Content-Length header already present
Run Code Online (Sandbox Code Playgroud)
UsernamePasswordCredentials defaultcreds = new UsernamePasswordCredentials(USER,
PASS);
HttpHost targetHost = new HttpHost("localhost", 8080, "http");
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
new UsernamePasswordCredentials(USER, PASS));
HttpPost httpPost = new HttpPost(urlSuffix) {};
JSONObject holder = new JSONObject();
holder.put("name", "this is a folder");
StringEntity se = new StringEntity(holder.toString());
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
httpPost.setEntity(se);
HttpResponse resp = httpclient.execute(targetHost,httpPost);
System.out.println("Resp->" + resp.getStatusLine().getStatusCode());
Run Code Online (Sandbox Code Playgroud)
我读过它因为我已经设置了两次内容长度,但我不确定如何解决它.
我意识到已经有一段时间了,因为这个问题已被提出,但是我找到的解决方案是:如果您无法更改客户端jar,我使用的解决方法是:
httpClient.removeRequestInterceptorByClass(org.apache.http.protocol.RequestContent.class);
Run Code Online (Sandbox Code Playgroud)
Apache的http客户端有一个请求拦截器,它自动计算并添加内容长度头,这也是由ws库完成的.使用上面的代码,此拦截器将从请求处理中排除.
| 归档时间: |
|
| 查看次数: |
12482 次 |
| 最近记录: |