gpt4 book ai didi

java - apache httpclient 内容长度问题

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:34:01 25 4
gpt4 key购买 nike

我正在尝试使用 Apache Httpclient 将一些 JSON 发布到休息服务。但是,我收到此错误:

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

我已经阅读了它,因为我已经设置了两次内容长度,但我不确定如何修复它。

最佳答案

我意识到自从有人提出这个问题以来已经有一段时间了,但这是我找到的解决方案:如果您无法更改客户端 jar,我使用的解决方法是:

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

Apache的http客户端有一个请求拦截器,自动计算并添加content length header,这也是ws库完成的。使用上面的代码,这个拦截器被排除在请求处理之外。

关于java - apache httpclient 内容长度问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5479760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com