android通过Http请求上传文件时文件名中文乱码

本文介绍如何处理Android应用通过HTTP上传包含中文名称的文件时出现的乱码问题。通过使用URLEncoder进行编码和解码,成功解决文件名中文乱码的难题。

项目中遇到了文件名含有中文时,手机端上传至服务器,接收到的文件名中文全是乱码,查找了许多方法,最终还是解决了,利用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");

即可得到正确的中文文件名。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值