MultipartEntityBuilder和setCharset为UTF-8发送内容为空 [英] MultipartEntityBuilder and setCharset for UTF-8 sends empty content

查看:3633
本文介绍了MultipartEntityBuilder和setCharset为UTF-8发送内容为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要提交UNI code字符形式来定位我的应用程序与非拉丁字母的国家。有一个关于新MultiPartEntityBuiler文档很少,我只发现了另外一个帖子建议使用setCharset。

如果我不使用Entity.setCharset(Consts.UTF_8);变量被转换成????? 当我使用Entity.setCharset(Consts.UTF_8);该变量是空白(空内容)。

下面是低于code。任何想法??

 进口android.os.AsyncTask;
进口android.util.Log;

进口java.io.BufferedReader中;
...
进口java.util.Map.Entry;

进口org.apache.http.Consts;
...
进口org.apache.http.util.EntityUtils;

公共类AsyncUploader {

    公共静态最终诠释ABORTED = -1,
                            ERROR = 1,
                            COMPLETE = 0;

    //公众最终诠释上传(字符串的URL,哈希表<字符串,字符串>数据,字符串名称,文件可上传)
    公众最终诠释上传(字符串的URL,哈希表<字符串,字符串>数据)
    {
        尝试
        {
            //如果(上载的== NULL ||!Uploadable.exists())
            //返回会;
            HttpPost后=新HttpPost(URL);

            MultipartEntityBuilder实体= MultipartEntityBuilder.create();

            // TODO为了避免单向code字对原来???但如果我们decomment变量是空的...
            //Entity.setCharset(Consts.UTF_8);

            如果(数据= NULL和放大器;!&安培; Data.size()0)
            {
                对于(进入<字符串,字符串>的NameValuePair:Data.entrySet())
                    Entity.addTextBody(NameValuePair.getKey(),NameValuePair.getValue(),ContentType.TEXT_PLAIN);
            }
            //Entity.addPart(Name,新FileBody(上载的));
            Post.setEntity(Entity.build());
            返回新_Uploader()执行(POST)获得()。
        }
        赶上(异常错误)
        {
            返回错误;
        }
    }

    私有静态类_Uploader
    扩展AsyncTask的<对象,太虚,整数GT;
    {
        @覆盖保护整数doInBackground(对象...参数)
        {
            尝试
            {
                如果(Parameters.length<!1 ||参数[0] == NULL ||(参数[0]的instanceof HttpPost))
                    抛出新的异常(传递参数未知参数);

                HttpPost请求=(HttpPost)参数[0];
                DefaultHttpClient客户端= NULL;
                HTT presponse响应= NULL;
                的InputStream流= NULL;

                尝试
                {
                    的HttpParams httpParameters =新BasicHttpParams();
                    HttpProtocolParams.setContentCharset(httpParameters,HTTP.UTF_8);
                    HttpProtocolParams.setHttpElementCharset(httpParameters,HTTP.UTF_8);
                    HttpProtocolParams.setUseExpectContinue(httpParameters,假);

                    System.setProperty(http.keepAlive,假);
                    客户端=新DefaultHttpClient(httpParameters);
                    Client.getParams()的setParameter(http.protocol.version,HttpVersion.HTTP_1_1)。
                    Client.getParams()的setParameter(http.protocol.content-字符集,HTTP.UTF_8)。

                    HTT prequestRetryHandler重试=新HTT prequestRetryHandler()
                    {
                        @覆盖公共布尔retryRequest(IOException异常错误,诠释计数,HttpContext的发件人)
                        {
                            如果(计数> = 2)
                                返回false;
                            如果(错误的instanceof NoHtt presponseException)
                                返回true;
                            否则,如果(错误的instanceof ClientProtocolException)
                                返回true;
                            返回false;
                        }
                    };

                    Client.setHtt prequestRetryHandler(重试);
                    响应= Client.execute(请求);
                    流= Response.getEntity()的getContent()。

                    //将code片来获取页面的内容
                    如果(Response.getStatusLine()的getStatus code()== HttpStatus.SC_OK){
                        StringBuilder的SB =新的StringBuilder();
                        尝试 {
                            的BufferedReader读卡器=新的BufferedReader(新的InputStreamReader(流),65728);
                            串线= NULL;
                            字符串bufferOutput = NULL;
                            而((线= reader.readLine())!= NULL)sb.append(线);

                            bufferOutput = sb.toString();

                            如果(bufferOutput.equals(OK))返回0;
                            否则返回ERR_OTHER;
                        }
                        赶上(IOException异常E){返回错误; }
                        赶上(例外五){返回错误; }
                    }
                    其他
                    {
                        返回Response.getStatusLine()的getStatus code()。
                    }
                }
                赶上(异常错误)
                {
                    返回错误;
                }
                最后
                {
                    尝试
                    {
                        如果(流!= NULL)
                            Stream.close();
                    }
                    赶上(异常错误)
                    {}
                    尝试
                    {
                        如果(响应=零和放大器;!&安培;!Response.getEntity()= NULL)
                            。Response.getEntity()consumeContent();
                    }
                    赶上(Throwable的错误)
                    {}
                    尝试
                    {
                        如果(客户端= NULL和放大器;!&安培;!Client.getConnectionManager()= NULL)
                            Client.getConnectionManager()关闭()。
                    }
                    赶上(Throwable的错误)
                    {}
                }
            }
            赶上(异常错误)
            {
                返回错误;
            }
        }
    }

}
 

解决方案

我遇到了同样的问题,发现了这个解决方案。

而不是使用addTextBody使用addPart与StringBody的。

 的ContentType的contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE,HTTP.UTF_8);
StringBody stringBody;
对于(进入<字符串,字符串>的NameValuePair:Data.entrySet()){
   stringBody =新StringBody(NameValuePair.getValue(),则contentType);
   Entity.addPart(NameValuePair.getKey(),stringBody);
}
 

反正这解决了这个问题对我来说。希望它能帮助。

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;
            }
        }
    }   

}

解决方案

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.

这篇关于MultipartEntityBuilder和setCharset为UTF-8发送内容为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆