开发者

apache httpclient content length issue

开发者 https://www.devze.com 2023-02-20 11:36 出处:网络
I am trying to post some JSON to a rest service using Apache Httpclient. However, I get this error : Exception in thread \"main\" org.apache.http.ProtocolException: Content-Length header already pres

I am trying to post some JSON to a rest service using Apache Httpclient. However, I get this error :

    Exception in thread "main" org.apache.http.ProtocolException: Content-Length header already present

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

I've read its because I'm setting the content length twice already, but I'm not sure how to fix it.


I realise it's been awhile since this question has been asked, but here's the solution I found: In case you cannot change the client jars, the workaround that I used is:

httpClient.removeRequestInterceptorByClass(org.apache.http.protocol.RequestContent.class);

Apache's http client has a request interceptor which automatically calculates and adds the content length header, which is also done by the ws library. With the code above, this interceptor is excluded from the request processing.


Your code works fine for me using HttClient 4.1.1. Which version are you using?

If you're certain that you aren't setting the Content-Length header a second time in your code (i.e. the code posted above is exactly the code you're running) then maybe you could try updating to the latest version of the httpclient library. You could possibly be experiencing an obscure bug like HTTPCLIENT-795.

0

精彩评论

暂无评论...
验证码 换一张
取 消