要上传文件到后台的php服务器,服务器能收到中文,手机发送过去,却只能收到一堆转了UTF-8的编码(就是要decode后才是中文的编码).android这边上传文件通常是用stream方式上传的,用MultipartEntity这个开源包来上传了会有编码问题.
首先设置字段的编码
//CustomMultiPartEntity entity=new CustomMultiPartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,null,Charset.forName("UTF-8"),listener);
//不需要构造函数,只要对应的文字是utf-8编码,传输是utf-8编码就可以
CustomMultiPartEntity multipartContent = new CustomMultiPartEntity(listener);entity.addPart(title, new StringBody(message,Charset.forName("UTF-8")));
entity.addPart(fileName,new FileBody(uploadFile));
listener.total(uploadFile.length());
http传输的编码
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;
}