我正在尝试使用Apache HttpClient5在Java程序中使用Web API。
使用一个简单的请求curl
:
curl -X POST -H "x-api-user: d904bd62-da08-416b-a816-ba797c9ee265" -H "x-api-key: xxxxxxxxxxx" https://habitica.com/api/v3/user/class/cast/valorousPresence
我得到了预期的响应和效果。
使用我的Java代码:
URI uri = new URIBuilder()
.setScheme("https")
.setHost("habitica.com")
.setPath("/api/v3/user/class/cast/valorousPresence")
.build();
Logger logger = LoggerFactory.getLogger(MyClass.class);
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(uri);
httpPost.addHeader(new BasicHeader("x-api-user",getApiUser()));
httpPost.addHeader(new BasicHeader("x-api-key", getApiKey()));
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
logger.info(httpResponse.toString());
return httpResponse.getCode();
运行Java调用时得到的输出是
411 Length Required HTTP/1.0
我确定我没有正确构建POST调用,应该怎么做?我尝试指定Content-Type,但没有效果。尝试在代码中设置Content-Length会导致编译错误(据我所知,这是由HttpClient5在后台处理的)。我所有使用HttpClient5的GET请求都可以正常工作。
一个POST
总是有一个有效载荷(内容)。POST
没有内容的A 很不寻常,那么您确定没有忘记什么吗?
您需要调用setEntity()
以设置有效负载,即使它是空的也是如此,因为它是设置Content-Length
标头的实体。
例如,您可以打电话httpPost.setEntity(new StringEntity(""))
,设置Content-Type: text/plain
和Content-Length: 0
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句