gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:07:28 24 4
gpt4 key购买 nike

我创建 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;
}
}

回答正确。

第二个请求(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 获取值或如何自动启用重定向。

最佳答案

由于设计限制,HttpClient 3.x 无法自动处理实体封装请求(例如 POST 和 PUT)的重定向。您要么必须在重定向时手动将 POST 请求转换为 GET,要么升级到 HttpClient 4.x,它可以自动处理所有类型的重定向。

关于java - 如何在 HttpClient 中自动重定向(java,apache),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5840707/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com