我创建了httpClient并设置了设置
HttpClient client = new HttpClient();
client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
client.getParams().setContentCharset("UTF-8");
第一次请求(获取)
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。
我不知道如何从Headers Location获取价值或如何自动启用重定向。
答案 0 :(得分:7)
由于设计限制,HttpClient 3.x无法自动处理封装请求(如POST和PUT)的实体的重定向。您必须在重定向时手动将POST请求转换为GET,或升级到HttpClient 4.x,它可以自动处理所有类型的重定向。
答案 1 :(得分:1)
对于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);
}
答案 2 :(得分:0)
答案 3 :(得分:0)
另外,您可以使用LaxRedirectStrategy