Why I am getting different HttpResponse than browser in android?

狂风中的少年 提交于 2020-01-03 07:11:52

问题


I am trying to get simple HTTP response from this URL : http://realtorsipad.demowebsiteonline.net/eventsfeed.php

But surprisingly it not returning expected XML response rather returning another HTML page!

I am not being able understand what is issue.

Here is sample activity :

public class MainActivity1 extends Activity {
    String parsingWebURL = "http://realtorsipad.demowebsiteonline.net/eventsfeed.php";
    String line = "";
    Document docXML;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        line = getXML();
        System.out.println(line);
    }

    // ------------------------------------------------
    public String getXML() {
        String strXML = "";
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(parsingWebURL);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            strXML = EntityUtils.toString(httpEntity);
            return strXML;
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return strXML;
    }
}

回答1:


It's not your code per se, it's the site, it responds with a lot of redirects when the request is made with a mobile user-agent.

To replicate a desktop browser, change your user agent string. Like so:

public String getXML() {
    String strXML = "";
    try {

        final HttpParams params = new BasicHttpParams();
        HttpClientParams.setRedirecting(params, true);
        HttpClientParams.setCookiePolicy(params, CookiePolicy.BROWSER_COMPATIBILITY);

        DefaultHttpClient httpClient = new DefaultHttpClient(params);
        httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:23.0) Gecko/20131011 Firefox/23.0");

        HttpGet httpGet = new HttpGet(parsingWebURL);

        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        strXML = EntityUtils.toString(httpEntity);
        return strXML;
    } catch (Exception e1) {
        e1.printStackTrace();
    }
    return strXML;
}


来源:https://stackoverflow.com/questions/17121123/why-i-am-getting-different-httpresponse-than-browser-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!