本文介绍了如何自动重定向HttpClient的(Java中,阿帕奇)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建的HttpClient并设置设置

I create httpClient and set settings

HttpClient client = new HttpClient();

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

第一个请求(获取)

First request (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;
    }
}

响应正确的。

第二个请求(后):

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。

this response is correct too, but I need to be redirected to Headers.Location.

我不知道如何从页眉位置或如何获得价值自动启用重定向。

I do not know how to get value from Headers Location or how to automatically enable redirection.

推荐答案

由于设计上的局限的HttpClient 3.x中无法自动处理实体内附请求,如POST的重定向和PUT。你要么必须POST请求重定向时手动转换为GET或升级到4.x版的HttpClient,它可以自动处理所有类型的重定向。

Due to design limitations HttpClient 3.x is unable to automatically handle redirects of entity enclosing requests such as POST and PUT. You either have to manually convert POST request to a GET upon redirect or upgrade to HttpClient 4.x, which can handle all types of redirects automatically.

这篇关于如何自动重定向HttpClient的(Java中,阿帕奇)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 20:07