Nikolas Sumrak
Nikolas Sumrak

Reputation: 110

Text encoding issue in Java Android app

I'm requesting some content from my website (in my Android app) using the following code:

response = httpClient.execute(httpPost, localContext);


// Pull content stream from response
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
InputStreamReader rd = new InputStreamReader(inputStream);
//ByteArrayOutputStream content = new ByteArrayOutputStream();
StringBuilder content = new StringBuilder();
int n = 0;
char[] buffer = new char[40000];
while (n >= 0)
{
        n = rd.read(buffer, 0, buffer.length);
        if (n > 0)
        {
            content.append(buffer, 0, n);
        }
}
ret = content.toString();

The content of the site is in encoded in the Windows-1251 encoding, but in the app I get a bunch of unreadable symbols, like so:

enter image description here

Also, the following code snippet doesn't seem to be working either:

text = new String(matcher.group(1).getBytes("Windows-1251"), "UTF-8");

enter image description here

Upvotes: 0

Views: 451

Answers (1)

Heshan Sandeepa
Heshan Sandeepa

Reputation: 3687

Try this ,

    BufferedReader reader = new BufferedReader(new InputStreamReader(in_stream), "UTF-8");
    StringBuilder content = new StringBuilder();
    String line = null;
    try
    {
        while ((line = reader.readLine()) != null) 
        {
            content.append(line + "\n");
        }

    } 
    catch (IOException e) 
    {
        e.printStackTrace();
    } 
    finally 
    {
        try 
        {
            in_stream.close();
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
    }
    ret = content.toString();

Upvotes: 1

Related Questions