Peter Olson
Peter Olson

Reputation: 143037

HttpGet sends request with the wrong encoding

I'm trying to get the text response from the following URL:

http://translate.google.cn/translate_a/single?client=t&sl=zh-CN&tl=en&dt=t&tk=265632.142896&q=%E4%BD%A0%E5%A5%BD

The response is the following:

[[["Hello there","你好",,,1]],,"zh-CN"]

(You can verify this response by entering the address into your browser.)

Here is a simplified version of my code that tries to download this text:

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

public class Test {
    public static String downloadString() {
        String url = "http://translate.google.cn/translate_a/single?client=t&sl=zh-CN&tl=en&dt=t&tk=265632.142896&q=%E4%BD%A0%E5%A5%BD";
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);
        ResponseHandler<String> handler = new BasicResponseHandler();
        try {
            return client.execute(request, handler);
        } catch (Exception e) {
            return "GET request failed.";
        }
    }
}

When I call Test.downloadString(), I get the following (incorrect) response:

[[["Huan Chai Sunsolt","浣犲ソ",,,0]],,"zh-CN"]

I'm guessing that there is some sort of encoding problem behind the scenes somewhere in the request process (there are six bytes that should be interpreted as two Chinese characters, but are instead interpreted as three Japanese characters), but I can't seem to pinpoint the exact cause. What am I doing wrong in my code?

Upvotes: 0

Views: 717

Answers (2)

virtual agent 07
virtual agent 07

Reputation: 126

It's strange, but adding the User-Agent header fixed the problem:

request.addHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:33.0) Gecko/20100101 Firefox/33.0");

Upvotes: 2

johnrao07
johnrao07

Reputation: 6938

Android 6.0 release removes support for the Apache HTTP client. If your app is using this client and targets Android 2.3 (API level 9) or higher, use the HttpURLConnection class instead.

here: http://developer.android.com/about/versions/marshmallow/android-6.0-changes.html#behavior-apache-http-client

Upvotes: 0

Related Questions