`
maoxy
  • 浏览: 139194 次
  • 性别: Icon_minigender_2
  • 来自: 广州
社区版块
存档分类
最新评论

URL编码问题

阅读更多

在使用java下载文件时,可能会遇到无法识别该地址,有一个原因就是编码问题。

 

public void DownloadFile(URL theURL, String filePath,String fileFullName) throws IOException {
		URLConnection con = theURL.openConnection();
		if (fileFullName != null) {
			byte[] buffer = new byte[4 * 1024];
			int read;
			String path = filePath + "/" + fileFullName;
			File fileFolder = new File(filePath);
			if(!fileFolder.exists()){
				fileFolder.mkdir();
			}
			InputStream in = con.getInputStream();
			FileOutputStream os = new FileOutputStream(path);
			while ((read = in.read(buffer)) > 0) {
				os.write(buffer, 0, read);
			}
			os.close();
			in.close();
			this.onStopFile(FILE_URL,"add",fileFullName,path);
		}else{
			Log.i("DownloadFile", "ERROR");
		}
	}

 

 上边的

 

InputStream in = con.getInputStream();

 

 就可能出错。


URL中本不应包含中文。 
如果包含中文,应当把中文字符变成字节(利用GB18030或者UTF-8等编码)。 

客户端转换的方式必须和服务器相同,比如服务器认为URL中的中文按照UTF-8编码,你的客户端就不能按照GB18030编码。 

如果是Tomcat,你需要修改server.xml。上网用“tomcat URIEncoding”关键字搜索,修改一个叫URIEncoding的东西。

如果是客户端则可以如下修改

 

 

String urlS = "http://172.18.33.133:8080/zh/中文.jpg";    
String host="http://172.18.33.133:8080/zh/";  
String filename=java.net.Encoder.encode("中文.jpg","服务器编码。");  
String urlS = host+filename;
URL theURL = new URL(urlS);
 

 

我就是这样解决的,有问题随时提出,不用谢!

 

0
3
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics