gpt4 book ai didi

java - 带有 CloseableHttpClient 的 POST 请求

转载 作者:搜寻专家 更新时间:2023-11-01 02:57:45 41 4
gpt4 key购买 nike

我正在尝试从一个简单的 Java 项目创建一个 HTTP POST 请求。

我需要通过两个请求保持 session 和 cookie,所以我选择了 Apache HttpClient .

代码编译没有错误并运行,但它返回零长度的内容,我不明白为什么。

public class Test {

private static final String CONTENT_TYPE = "Content-Type";
private static final String FORM_URLENCODED = "application/x-www-form-urlencoded";

public static void main(String[] args) {

try {

CloseableHttpClient httpClient = HttpClients.createDefault();

BasicHttpContext httpCtx = new BasicHttpContext();
CookieStore store = new BasicCookieStore();
httpCtx.setAttribute(HttpClientContext.COOKIE_STORE, store);

String url = "http://myhost:port/app/";
String body = "my body string";

HttpPost httpPost = new HttpPost(url);
httpPost.setHeader(CONTENT_TYPE, FORM_URLENCODED);
StringEntity entity = new StringEntity(body);

httpPost.setEntity(entity);
CloseableHttpResponse response = httpClient.execute(httpPost, httpCtx);
HttpEntity respentity = response.getEntity();

System.out.println("respentity: " + respentity);

System.out.println("EntityUtils.toString(respentity): " + EntityUtils.toString(respentity));

EntityUtils.consume(respentity);

System.out.println("respentity: " + respentity);
System.out.println("EntityUtils.toString(respentity): " + EntityUtils.toString(respentity));

} catch (Exception ex) {
ex.printStackTrace();
}

}

}

结果是:

respentity: [Content-Length: 0,Chunked: false]
EntityUtils.toString(respentity):
respentity: [Content-Length: 0,Chunked: false]
EntityUtils.toString(respentity):

更新:我发现响应状态是 302(已找到),当我从 Postman 执行相同的请求时,它是 200(OK).

有人能告诉我我的代码有什么问题吗?

谢谢

最佳答案

默认情况下,只会自动遵循导致重定向的 GET 请求。如果 POST 请求以 HTTP 301 Moved Permanently302 Found 响应,则不会自动遵循重定向。

这是由 HTTP RFC 2616 指定的:

If the 301 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.

使用HttpClient 4.2(或更高版本),我们可以将重定向策略设置为LaxRedirectStrategy ,此策略放宽了 HTTP 规范强加的对 POST 方法自动重定向的限制。

因此您可以使用如下方法创建 CloseableHttpClient 实例:

private CloseableHttpClient createHttpClient() {
HttpClientBuilder builder = HttpClientBuilder.create();
return builder.setRedirectStrategy(new LaxRedirectStrategy()).build();
}

并用它来管理 POST 请求。

关于java - 带有 CloseableHttpClient 的 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49066687/

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