使用CloseableHttpClient发出POST请求

问题描述 投票:3回答:1

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

我需要通过两个请求保持会话和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(Found),当我从Postman做同样的请求时它是200(OK)。

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

谢谢

java apache-httpclient-4.x
1个回答
2
投票

默认情况下,只会自动跟踪导致重定向的GET请求。如果使用POSTHTTP 301 Moved Permanently回答302 Found请求,则不会自动遵循重定向。

这由HTTP RFC 2616指定:

如果收到301状态代码以响应GET或HEAD以外的请求,则用户代理不得自动重定向请求,除非用户可以确认,因为这可能会改变发出请求的条件。

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

所以你可以使用如下方法创建CloseableHttpClient实例:

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

并使用它来管理POST请求。

© www.soinside.com 2019 - 2024. All rights reserved.