项目中遇到了文件名含有中文时,手机端上传至服务器,接收到的文件名中文全是乱码,查找了许多方法,最终还是解决了,利用URLEncoder编码、解码的办法。
相关代码的片段:
String end = "\r\n";
String twoHyphens = "--";
String boundary = "******";
try {
URL url = new URL(uploadUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setConnectTimeout(6*1000);
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
DataOutputStream dos = new DataOutputStream(httpURLConnection
.getOutputStream());
dos.writeBytes(twoHyphens + boundary + end);
dos
.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""
+ encode(filePath.substring(filePath.lastIndexOf("/") + 1))
+ "\"" + end);
dos.writeBytes(end);在这里,对文件名加以编码,方法为:
// 对包含中文的字符串进行转码,此为UTF-8。服务器那边要进行一次解码
private String encode(String value) throws Exception{
return URLEncoder.encode(value, "utf-8");
}服务器端的解码只需要:
String filename = URLDecoder.decode(filename, "utf-8");即可得到正确的中文文件名。
本文介绍如何处理Android应用通过HTTP上传包含中文名称的文件时出现的乱码问题。通过使用URLEncoder进行编码和解码,成功解决文件名中文乱码的难题。
3303

被折叠的 条评论
为什么被折叠?



