MultipartEntityBuilder and setCharset for UTF-8 se

2019-04-30 05:14发布

问题:

I need to submit unicode characters to a form to localize my app to countries with non latin alphabet. There is little documentation about the new MultiPartEntityBuiler and I only found one other post suggesting to use setCharset.

If I don't use Entity.setCharset(Consts.UTF_8); the variables are transformed into "?????" When I use Entity.setCharset(Consts.UTF_8); the variables are blanked (empty content).

Here is the code below. Any idea??

import android.os.AsyncTask;
import android.util.Log;

import java.io.BufferedReader;
...
import java.util.Map.Entry;

import org.apache.http.Consts;
...
import org.apache.http.util.EntityUtils;

public class AsyncUploader {

    public static final int ABORTED  =  -1,
                            ERROR    = 1, 
                            COMPLETE =   0;

    //public final int Upload(String Url, Hashtable<String, String> Data, String Name, File Uploadable)
    public final int Upload(String Url, Hashtable<String, String> Data)
    {       
        try
        {
            //if (Uploadable == null || !Uploadable.exists())
            //return ABORTED;           
            HttpPost Post = new HttpPost(Url);

            MultipartEntityBuilder Entity = MultipartEntityBuilder.create();

            // TODO To avoid unicode characters turned unto ??? but if we decomment variables are empty...
            //Entity.setCharset(Consts.UTF_8);

            if (Data != null && Data.size() > 0)
            {
                for (Entry<String, String> NameValuePair : Data.entrySet())
                    Entity.addTextBody(NameValuePair.getKey(), NameValuePair.getValue(), ContentType.TEXT_PLAIN);
            }
            //Entity.addPart(Name, new FileBody(Uploadable));
            Post.setEntity(Entity.build());
            return new _Uploader().execute(Post).get();
        }
        catch (Exception Error)
        {
            return ERROR;
        }
    }

    private static class _Uploader
    extends AsyncTask<Object, Void, Integer>
    {
        @Override protected Integer doInBackground(Object... Parameters)
        {
            try
            {
                if (Parameters.length < 1 || Parameters[0] == null || !(Parameters[0] instanceof HttpPost))
                    throw new Exception("Unknown parameter passed in arguments");

                HttpPost Request = (HttpPost) Parameters[0];
                DefaultHttpClient   Client      = null;
                HttpResponse        Response    = null;
                InputStream         Stream      = null;

                try
                {
                    HttpParams httpParameters = new BasicHttpParams();
                    HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);
                    HttpProtocolParams.setHttpElementCharset(httpParameters, HTTP.UTF_8);
                    HttpProtocolParams.setUseExpectContinue(httpParameters, false);

                    System.setProperty("http.keepAlive", "false");
                    Client = new DefaultHttpClient(httpParameters);
                    Client.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
                    Client.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8);

                    HttpRequestRetryHandler Retry = new HttpRequestRetryHandler()
                    {
                        @Override public boolean retryRequest(IOException Error, int Count, HttpContext Sender)
                        {
                            if (Count >= 2)
                                return false;
                            if (Error instanceof NoHttpResponseException)
                                return true;
                            else if (Error instanceof ClientProtocolException)
                                return true;
                            return false;
                        }
                    };

                    Client.setHttpRequestRetryHandler(Retry);
                    Response    = Client.execute(Request);
                    Stream      = Response.getEntity().getContent();

                    // Piece of code to get the content of the page
                    if( Response.getStatusLine().getStatusCode() == HttpStatus.SC_OK ) {
                        StringBuilder sb = new StringBuilder();
                        try {
                            BufferedReader reader = new BufferedReader(new InputStreamReader(Stream), 65728);
                            String line = null;
                            String bufferOutput = null;
                            while ((line = reader.readLine()) != null) sb.append(line);

                            bufferOutput = sb.toString();

                            if( bufferOutput.equals("OK") ) return 0;
                            else return ERR_OTHER;
                        }
                        catch (IOException e) { return ERROR; }
                        catch (Exception e) { return ERROR; }
                    }
                    else
                    {
                        return Response.getStatusLine().getStatusCode();
                    }
                }
                catch (Exception Error)
                {
                    return ERROR;
                }
                finally
                {
                    try
                    {
                        if (Stream != null)
                            Stream.close();
                    }
                    catch (Exception Error)
                    { }
                    try
                    {
                        if (Response != null && Response.getEntity() != null)
                            Response.getEntity().consumeContent();
                    }
                    catch (Throwable Error)
                    { }
                    try
                    {
                        if (Client != null && Client.getConnectionManager() != null)
                            Client.getConnectionManager().shutdown();
                    }
                    catch (Throwable Error)
                    { }
                }
            }
            catch (Exception Error)
            {
                return ERROR;
            }
        }
    }   

}

回答1:

I ran into the same problem and found this solution.

Instead of using addTextBody use addPart with a StringBody.

ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
StringBody stringBody; 
for (Entry<String, String> NameValuePair : Data.entrySet()){
   stringBody = new StringBody(NameValuePair.getValue(), contentType);
   Entity.addPart(NameValuePair.getKey(), stringBody);
}

Anyways this solved the issue for me. Hope it helps.



回答2:

In my case, I setup the contentType first like this

ContentType contentType = ContentType.create(
                        HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);

and when adding pairs , specify the content type like this

entityBuilder.addTextBody("title",pic.getTitle(),contentType);

Hope this help



回答3:

You can just use addTextBody with more specified content type.

ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
for (Entry<String, String> NameValuePair : Data.entrySet()){
   Entity.addTextBody(NameValuePair.getKey(), NameValuePair.getValue(), contentType);
}