Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在HttpClient(java、apache)中自动重定向_Java_Apache_Httpclient - Fatal编程技术网

如何在HttpClient(java、apache)中自动重定向

如何在HttpClient(java、apache)中自动重定向,java,apache,httpclient,Java,Apache,Httpclient,我创建httpClient并设置设置 HttpClient client = new HttpClient(); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); client.getParams().setContentCharset("UTF-8"); 第一个请求(get) 回答正确 第二项请求(员额): 此响应也是正确的,但我需要重定向到Headers.Location 我不知道如何从标题位置

我创建httpClient并设置设置

HttpClient client = new HttpClient();

client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
client.getParams().setContentCharset("UTF-8");
第一个请求(get)

回答正确

第二项请求(员额):

此响应也是正确的,但我需要重定向到Headers.Location


我不知道如何从标题位置获取值或如何自动启用重定向。

您只需要添加以下内容:

second.setFollowRedirects(true);

由于设计限制,HttpClient 3.x无法自动处理包含POST和PUT等请求的实体重定向。您必须手动将POST请求转换为GET-On重定向,或者升级到HttpClient 4.x,它可以自动处理所有类型的重定向。

此外,对于3.x版本的HttpClient,您也可以使用
LaxRedirectStrategy
,您还可以检查响应代码是301还是302,然后使用位置标题重新发布:

client.executeMethod(post);
int status = post.getStatusCode();
if (status == 301 || status == 302) {
  String location = post.getResponseHeader("Location").toString();
  URI uri = new URI(location, false);
  post.setURI(uri);
  client.executeMethod(post);
}
错误-“在没有用户干预的情况下,无法重定向包含请求的实体”
second.setFollowRedirects(true);
client.executeMethod(post);
int status = post.getStatusCode();
if (status == 301 || status == 302) {
  String location = post.getResponseHeader("Location").toString();
  URI uri = new URI(location, false);
  post.setURI(uri);
  client.executeMethod(post);
}