httpclient重定向和post
时间: 2023-08-23 07:30:51 浏览: 47
当使用HttpClient库发送POST请求时,如果服务器返回重定向响应,可以通过设置HttpClient实例的重定向策略来自动处理重定向。默认情况下,HttpClient实例会禁用自动重定向,可以使用`setRedirectStrategy()`方法来启用自动重定向。例如:
```java
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
// 设置请求参数
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("param1", "value1"));
params.add(new BasicNameValuePair("param2", "value2"));
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
// 设置重定向策略
LaxRedirectStrategy redirectStrategy = new LaxRedirectStrategy();
httpClient = HttpClients.custom().setRedirectStrategy(redirectStrategy).build();
// 发送POST请求
CloseableHttpResponse response = httpClient.execute(httpPost);
```
在上述代码中,我们使用`setRedirectStrategy()`方法将重定向策略设置为`LaxRedirectStrategy`,这个策略不会自动重定向POST请求,但是会自动重定向GET请求。
如果你想在重定向时保留POST请求的请求体,需要将HTTP方法设置为`LaxRedirectStrategy`时自动重定向POST请求,但是会将请求体作为GET请求的查询参数添加到重定向URL中。如果你想保留请求体的话,需要在`LaxRedirectStrategy`的实例中重写`getRedirect()`方法,自己实现POST请求的重定向。