利用MultipartEntity上传文件碰到的中文转编码的问题.

时间:2022-08-28 19:31:58

之前碰到一个问题,要上传文件到后台的php服务器.同样的API,在iOS那边传过去,服务器能收到中文,但我这边发送过去,却只能收到一堆转了UTF-8的编码(就是要decode后才是中文的编码).我们android这边上传文件通常是用stream方式上传的,但这次后台不肯改,只收文件,那只好用MultipartEntity这个开源包来上传了,但是却遇到了编码问题.搞了很久(足足一个月了),终于在各种尝试下找到解决方法了,以下是方法,其实关键代码就一句.


CustomMultiPartEntity entity=new CustomMultiPartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,null,Charset.forName("UTF-8"),listener);
entity.addPart(title, new StringBody(message,Charset.forName("UTF-8")));
entity.addPart(fileName,new FileBody(uploadFile));
listener.total(uploadFile.length());

这个CustomMultiPartEntity是我重写过MultipartEntity的,用listener来实现监听下载百分比的.


public static String getUploadRequest(String url,MultipartEntity entity){
String result=null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
HttpParams params = httpclient.getParams();
params.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, Charset.forName("UTF-8"));//關鍵的一句,讓API識別到charset
HttpConnectionParams.setConnectionTimeout(params, 10*1000);//连接超时
HttpConnectionParams.setSoTimeout(params, 10*1000);//读取数据超时
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
result = EntityUtils.toString( resEntity, HTTP.UTF_8);
Log.e(TAG, "result:"+result);
return result;
}
if(resEntity!=null){
resEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
return result;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}

然后就是添加entity的时候,记得在他之前设好parameter. 加了那一句,后台就能收到中文了.