Characters rendered incorrectly in HttpEntity resp

2019-05-28 09:24发布

I'm doing little app that receives some XML with UTF-8 encoding, the very same XML in browser renders characters correctly whereas in Android I've got some "Garbage" eg. WÅochy instead of Włochy or Dwójka instead of Dwójka. Apparently I'm doing something wrong, can anyone help me figuring it out?

Best regards

String response = EntityUtils.toString( resEntity ).trim();
Log.i( CLASS_NAME, "RESPONSE=" + response );
//This returns response with incorrectly rendered characters eg. WÅochy instead of Włochy

Following is the code that sends POST request and receives response, it is run in AsyncTask:

protected Document doInBackground(ServiceQuery... queries)
{
    if ( m_sGateway == null ) return null;

    Document result = null;

    try
    {
        HttpClient client = new DefaultHttpClient();

        HttpPost post = new HttpPost( m_sGateway );

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add( new BasicNameValuePair( "mdsXML", queries[0].getQueryString() ) );

        UrlEncodedFormEntity ent = new UrlEncodedFormEntity( params, HTTP.UTF_8 );
        post.setEntity( ent );
        HttpResponse responsePOST = client.execute( post );

        HttpEntity resEntity = responsePOST.getEntity();

        if ( resEntity != null )
        {
            Log.i( CLASS_NAME, "contentLength:" + resEntity.getContentLength() );
            Log.i( CLASS_NAME, "getContentEncoding():" + resEntity.getContentEncoding() );
            Log.i( CLASS_NAME, "getContentEncoding().isChunked():" + resEntity.isChunked() );
            Log.i( CLASS_NAME, "getContentEncoding().isRepeatable():" + resEntity.isRepeatable() );

            String response = EntityUtils.toString( resEntity ).trim();

            Log.i( CLASS_NAME, "RESPONSE=" + response );//This returns response with incorrectly rendered characters eg. WÅochy instead of Włochy


            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();

            InputStream is = new ByteArrayInputStream( response.getBytes(HTTP.UTF_8) );


            result = db.parse( is );
            result.getDocumentElement().normalize();
        }

    }
    catch (Exception e)
    {
        e.printStackTrace();
        Log.e( CLASS_NAME, "doInBackground error." );
        result = null;
    }

    return result;
}

1条回答
The star\"
2楼-- · 2019-05-28 09:38

credits for an answer to my problem goes to Paul Grime.

import org.apache.http.util.EntityUtils;

String response = EntityUtils.toString( resEntity, HTTP.UTF_8 );

where resEntity is HttpEntity instance.

查看更多
登录 后发表回答