tandaica0612
tandaica0612

Reputation: 371

Read body return from HttpResponse unstable in java?

I have a project need get livescores result over the internet. After research i have found that i can get livescore from http://iphone.livescore.com/iphone.dll?gmt=0.0 . Then after that i write a simple application that get responded from the url above. But the problem is my code write to get result work unstable. Sometime it return body of the url not correct as the browser display, in my application it show unknow string with character that human can't readable.

Here my code, can some one can give me a advise?

private String getURLContent(String url) {
    StringBuffer stringBuffer = new StringBuffer();

    HttpGet httpGet = new HttpGet(url);
    try {
        HttpResponse response = httpClient.execute(httpGet);
        if (response.getStatusLine().getStatusCode() == 200) {
            InputStream inputStream = response.getEntity().getContent();

            InputStreamReader reader = new InputStreamReader(inputStream,
                    "UTF-8");
            int ch;
            while ((ch = reader.read()) > -1) {
                stringBuffer.append((char) ch);
            }
            reader.close();
        }
    } catch (ClientProtocolException e) {
        log.fatal(e);
    } catch (IOException e) {
        log.fatal(e);
    }
    return stringBuffer.toString();
}

Upvotes: 0

Views: 736

Answers (1)

iTech
iTech

Reputation: 18440

Make sure that the server sends data in UTF-8 format.

Beside this I would replace the read code with this one-liner:

EntityUtils.toString(response.getEntity(),"UTF-8");

Upvotes: 3

Related Questions