Java HttpClient 跟随重定向
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18320025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HttpClient follow redirect
提问by chrizz42
I am currently working on little project. The aim of the project is to log in to a website and get/handle the information on the site. Moreover, I would like to open some links and search through them as well.
我目前正在做一个小项目。该项目的目的是登录网站并获取/处理网站上的信息。此外,我想打开一些链接并搜索它们。
The server side looks like this:
服务器端看起来像这样:
You need to login to a php site. When sucessfully login you get a session and will be redirected to foo.username.bar.php (changed).
您需要登录到一个 php 站点。成功登录后,您将获得一个会话并将被重定向到 foo.username.bar.php(已更改)。
With this code:
使用此代码:
BufferedReader in = null;
String data = null;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", user));
nameValuePairs.add(new BasicNameValuePair("passwort", pass));
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(website);
request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while ((l = in.readLine()) != null) {
sb.append(l + nl);
}
in.close();
data = sb.toString();
return data;
} finally {
if (in == null) {
try {
in.close();
return "ERROR";
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
I sucessfully logged into the website. However, I can only see the page source of the php user confirmation site which tells me that I was sucessfully logged in and will be redirected.
我成功登录了该网站。但是,我只能看到php用户确认站点的页面源,它告诉我我已成功登录并将被重定向。
Now I actually want to see the page source where I was redirected too and keep the connection in order to open some more links on that page.
现在我实际上也想查看我被重定向的页面源并保持连接以便在该页面上打开更多链接。
Do you guys have an Idea how I can solve this?
你们有什么想法我该如何解决这个问题?
采纳答案by jtravaglini
You need to follow the redirect (status 302) returned by the response. Check out this answer.
您需要遵循响应返回的重定向(状态 302)。看看这个答案。