我HttpClient version 4.2.5
用于向 URL 发出 post 请求http://lirr42.mta.info/index.php
这个 url 正在重定向到 schedules.php,最后我期待所有预定的火车时间细节的结果。
实施后LaxRedirectStrategy
,我得到了正确的响应代码,200
而不是302
. 但问题是我没有从schedules.php
(重定向的 url)获得响应,而是从index.php
(1st url)获得以下响应,仅参数我发送的内容。
FromStation=56&ToStation=8&RequestDate=09%2F07%2F2013&RequestAMPM=PM&RequestTime=01%3A00&sortBy=1&schedules=schedules
请帮我解决问题。
public static void main(String[] args) throws Exception {
getPageHttpClient("http://lirr42.mta.info/index.php");
}
public static String getPageHttpClient(String url) throws IOException {
DefaultHttpClient httpclient = new DefaultHttpClient();
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("FromStation", "56"));
formparams.add(new BasicNameValuePair("ToStation", "8"));
formparams.add(new BasicNameValuePair("RequestDate", "09/07/2013"));
formparams.add(new BasicNameValuePair("RequestAMPM", "PM"));
formparams.add(new BasicNameValuePair("RequestTime", "01:00"));
formparams.add(new BasicNameValuePair("sortBy", "1"));
formparams.add(new BasicNameValuePair("schedules", "schedules"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
HttpPost httppost = new HttpPost(url);
httppost.setEntity(entity);
HttpContext localContext = new BasicHttpContext();
httpclient.setRedirectStrategy(new LaxRedirectStrategy());
HttpResponse response = httpclient.execute(httppost, localContext);
HttpUriRequest currentReq = (HttpUriRequest) localContext.getAttribute(
ExecutionContext.HTTP_REQUEST);
HttpHost currentHost = (HttpHost) localContext.getAttribute(
ExecutionContext.HTTP_TARGET_HOST);
String currentUrl = currentHost.toURI() + currentReq.getURI();
System.out.println(currentUrl);
System.out.println(response);
HttpEntity httpEntity = response.getEntity();
String str = "";
if (httpEntity != null) {
str = EntityUtils.toString(entity);
System.out.println(str);
}
return str;
}
程序响应:
http://lirr42.mta.info/schedules.php
HTTP/1.1 200 OK [Date: Fri, 06 Sep 2013 20:01:53 GMT, Server: Apache/2.2.3 (Linux/SUSE), X-Powered-By: PHP/5.2.5, Expires: 0, Cache-Control: no-cache, Pragma: no-cache, Content-Type: text/html, Content-Length: 15832, Age: 1, Via: 1.1 localhost.localdomain]
FromStation=56&ToStation=8&RequestDate=09%2F07%2F2013&RequestAMPM=PM&RequestTime=01%3A00&sortBy=1&schedules=schedules