简体   繁体   中英

Android vs. Java on PC : Different HttpResponse?

I run SAME code on my PC (windows 7 64 bit, Eclipse, Java) and on a Android Virtual Machine and I get different results.

Its a small programm that shoult print me the HttpResponse fully as String.

Results on PC:

HTTP/1.1 405 Method Not Allowed [Allow: GET, HEAD, Date: Thu, 03 Nov 2011 17:57:22 GMT, Content-Type: text/html; charset=UTF-8, Server: gws, Content-Length: 11816, X-XSS-Protection: 1; mode=block, X-Frame-Options: SAMEORIGIN]

Result on Android:

org.apache.http.message.BasicHttpResponse@44ec9da8

The code I ran on PC was:

HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(
            "http://www.google.com");

    try {
        HttpResponse response = httpclient.execute(httppost);
        System.out.println(response.toString());

And on Android:

HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(
            "http://www.google.com");

    try {
        HttpResponse response = httpclient.execute(httppost);
        return response.toString();

Im asking becasue I wrote a App that would work on PC - works with the HttpResponse content - but on android it seems that is has NO content at all...

Could anyone please explain me this? Or tell me how to get the response content (headers) as String on android?

This is because HttpResponse.toString() is implemented differently on Android and on PC (different jvm and framework components implementations!). To get HttpHeaders correctly I guess you need to use something like:

http://developer.android.com/reference/org/apache/http/HttpMessage.html#getAllHeaders%28%29

Anyhow see javadoc for reference on this.

You don't actually run the same code.

Android's BasicHttpResponse currently has no toString() method at all and goes on to invoke java.lang.Object.toString() giving you fully.qualified.class.name@hashcode .

Your desktop version of HttpClient most likely has a toString() similar to this one from HttpClient 4.1.3 :

public String toString() {
    return this.statusline + " " + this.headergroup;
}

Using toString() for any non-debugging/logging purposes isn't good practice -- you should extract the right information using actual get methods or just return the HttpResponse itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM