2013-11-26 13 views
5

Devo inviare caratteri unicode a un modulo per localizzare la mia app in paesi con alfabeto non latino. C'è poca documentazione sul nuovo MultiPartEntityBuiler e ho trovato solo un altro post che suggerisce di utilizzare setCharset.MultipartEntityBuilder e setCharset per UTF-8 invia contenuto vuoto

Se non utilizzo Entity.setCharset (Consts.UTF_8); le variabili vengono trasformate in "?????" Quando uso Entity.setCharset (Consts.UTF_8); le variabili sono oscurate (contenuto vuoto).

Ecco il codice qui sotto. Qualche 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; 
      } 
     } 
    } 

} 

risposta

5

Ho incontrato lo stesso problema e ho trovato questa soluzione.

Invece di utilizzare addTextBody, utilizzare addPart con 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); 
} 

In ogni caso questo ha risolto il problema per me. Spero che sia d'aiuto.

+0

Qual è la differenza con: 'Entity.addTextBody (NameValuePair.getKey(), NameValuePair.getValue(), contentType); '? –

1

Si può semplicemente usare addTextBody con un tipo di contenuto più specifico.

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); 
} 
+2

(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8) è deprecato. È possibile utilizzare: ContentType.create ("text/plain", Charset.forName ("UTF-8")) – GeneralKimi

3

Nel mio caso, ho configurato il contentType prima come questo

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

e quando si aggiungono le coppie, specificare il tipo di contenuto come questo

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

Spero che questo aiuto