Java – Apache httpclient content length problem

I tried to publish some JSON to the rest service using Apache httpclient However, I received 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 it because I've set the content length twice, but I'm not sure how to solve it

Solution

Using httclient 4.1 1. Your code can be used normally Which version are you using?

If you are sure that the content length header is not set in the code for the second time (that is, the code published above is the code you are running), you can try to update to the latest version of httpclient library You may encounter an ambiguous error like HTTP client - 795

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>