标签:httpclient android使用httpclient上
使用过HttpClient的人都知道可以通过addTextBody方法来添加要上传的文本信息,但是,如果要上传中文的话,或还有中文名称的文件会出现乱码的问题,解决办法其实很简单:
第一步:设置MultipartEntityBuilder的编码方式为UTF-8。
builder.setCharset(Charset.forName(HTTP.UTF_8));//设置请求的编码格式
第二步:创建ContentType对象,指定UTF-8编码。
ContentType contentType= ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
第三步:使用addPart+ StringBody代替addTextBody。如:
StringBody stringBody=new StringBody("中文乱码",contentType);
builder.addPart("test",stringBody);ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);      
HttpClient client=new DefaultHttpClient();// 开启一个客户端 HTTP 请求 
HttpPost post = new HttpPost(url);//创建 HTTP POST 请求  
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(Charset.forName(HTTP.UTF_8));//设置请求的编码格式
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//设置浏览器兼容模式
int count=0;
for (File file:files) {
//			FileBody fileBody = new FileBody(file);//把文件转换成流对象FileBody
//			builder.addPart("file"+count, fileBody);
	builder.addBinaryBody("file"+count, file);
	count++;
}		
builder.addTextBody("method", params.get("method"));//设置请求参数
builder.addTextBody("fileTypes", params.get("fileTypes"));//设置请求参数
StringBody stringBody=new StringBody("中文乱码",contentType);
builder.addPart("test", stringBody);
HttpEntity entity = builder.build();// 生成 HTTP POST 实体  	
post.setEntity(entity);//设置请求参数
HttpResponse response = client.execute(post);// 发起请求 并返回请求的响应
if (response.getStatusLine().getStatusCode()==200) {
	return true;
}
return false;标签:httpclient android使用httpclient上
原文地址:http://blog.csdn.net/fengyuzhengfan/article/details/40792529