Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I am getting different HttpResponse than browser in android?

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;
    }
}
like image 370
Nik88 Avatar asked Jun 15 '13 07:06

Nik88


1 Answers

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;
}
like image 88
Ken Wolf Avatar answered Oct 25 '22 00:10

Ken Wolf