我需要遵循HTTPost给我的重定向。当我发布HTTP帖子并尝试阅读响应时,我获得了重定向页面html。我怎样才能解决这个问题?代码:
public void parseDoc() {
final HttpParams params = new BasicHttpParams();
HttpClientParams.setRedirecting(params, true);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"https://secure.groupfusion.net/processlogin.php");
String HTML = "";
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("referral_page",
"/modules/gradebook/ui/gradebook.phtml?type=student_view"));
nameValuePairs.add(new BasicNameValuePair("currDomain",
"beardenhs.knoxschools.org"));
nameValuePairs.add(new BasicNameValuePair("username", username
.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("password", password
.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
String g = httppost.getURI().toString();
HttpResponse response = httpclient.execute(httppost);
HTML = EntityUtils.toString(response.getEntity());
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String ResponseBody = httpclient.execute(httppost, responseHandler);
sting.setText(HTML);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
答案 0 :(得分:7)
当服务器发送重定向时,它实际上是发送一个指示重定向的3xx响应代码(通常为301或302),以及一个告诉您新位置的Location头。
因此,在您的情况下,您可以从HttpResponse对象获取Location标头,并使用它来发送另一个请求以在您登录后检索实际内容。例如:
String newUrl = response.getFirstHeader("Location").getValue();
只要为两个请求重复使用相同的HttpClient对象,它就应该使用后续请求中登录请求设置的任何cookie。
答案 1 :(得分:3)