如何在HttpClient (Java, Apache)中自动重定向

6

我创建了httpClient并设置了相关的配置

HttpClient client = new HttpClient();

client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
client.getParams().setContentCharset("UTF-8");

首次请求(get)

GetMethod first = new GetMethod("http://vk.com");
int returnCode = client.executeMethod(first);

BufferedReader br = null;
String lineResult = "";
if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
    System.err.println("The Post method is not implemented by this URI");
    // still consume the response body
    first.getResponseBodyAsString();
} else {
    br = new BufferedReader(new InputStreamReader(first.getResponseBodyAsStream(), Charset.forName("windows-1251")));
    String readLine = "";
    while (((readLine = br.readLine()) != null)) {
        lineResult += readLine;
    }
}

响应正确。

第二个请求(post):

PostMethod second = new PostMethod("http://login.vk.com/?act=login");

second.setRequestHeader("Referer", "http://vk.com/");

second.addParameter("act", "login");
second.addParameter("al_frame", "1");
second.addParameter("captcha_key", "");
second.addParameter("captcha_sid", "");
second.addParameter("expire", "");
second.addParameter("q", "1");
second.addParameter("from_host", "vk.com");
second.addParameter("email", email);
second.addParameter("pass", password);

returnCode = client.executeMethod(second);

br = null;
lineResult = "";
if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
    System.err.println("The Post method is not implemented by this URI");
    // still consume the response body
    second.getResponseBodyAsString();
} else {
    br = new BufferedReader(new InputStreamReader(second.getResponseBodyAsStream()));
    String readLine = "";
    while (((readLine = br.readLine()) != null)) {
        lineResult += readLine;
    }
}

这个响应也是正确的,但我需要被重定向到Headers.Location。

我不知道如何从Headers Location中获取值,也不知道如何自动启用重定向。

4个回答

7

由于设计限制,HttpClient 3.x无法自动处理POST和PUT等实体封装请求的重定向。您需要手动将POST请求转换为GET请求进行重定向,或者升级到可以自动处理所有类型重定向的HttpClient 4.x。


2

如果使用3.x版本的HttpClient,您可以检查响应代码是否为301或302,然后使用Location标头进行重新发布:

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);
}

你可能需要使用 post.getResponseHeader("Location").getValue(); - Dilini

0

你只需要添加这个:

second.setFollowRedirects(true);

6
错误 - “实体封装请求不能在没有用户干预的情况下重定向” - Mediator

0

此外,您可以使用LaxRedirectStrategy


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接