【发布时间】:2018-03-02 21:21:13
【问题描述】:
我正在尝试从一个简单的 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(已找到),当我从 Postman 发出相同的请求时,它是 200(OK) >.
谁能告诉我我的代码有什么问题吗?
谢谢
【问题讨论】:
标签: java apache-httpclient-4.x