0

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
4

1 回答 1

1

您得到了正确的响应,只是没有正确打印。

那是因为你EntityUtils.toString()entity而不是httpEntity.

这里

HttpEntity httpEntity = response.getEntity();
String str = "";
if (httpEntity != null) {
    str = EntityUtils.toString(entity);
    System.out.println(str);
}

你通过entity

UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");

IE。参数。

利用

str = EntityUtils.toString(httpEntity);

获取HttpResponse内容。

于 2013-09-06T20:28:56.013 回答