带有中文字符的无效URI(Java) [英] Invalid URI with Chinese characters (Java)

查看:432
本文介绍了带有中文字符的无效URI(Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在网址中设置包含中文字符的网址连接时遇到问题。它适用于拉丁字符:

Having trouble setting up a URL connection with Chinese characters in the URL. It works with Latin characters:

String xstr = "维也纳恩斯特哈佩尔球场" ;
URI uri = new URI("http","ajax.googleapis.com","/ajax/services/language/detect","v=1.0&q="+xstr,null);   
URL url = uri.toURL(); 
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream() ;

getInputStream()调用结果为:

The getInputStream() call results in:

java.lang.IllegalArgumentException: Invalid uri 'http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q=???????????': Invalid query


推荐答案

问题是由于 URI.toURL()不对非ASCII字符进行百分比编码。请改用以下内容:

The problem is caused by the fact that URI.toURL() doesn't percent-encode non-ASCII characters. Use the following instead:

URL url = new URL(uri.toASCIIString());  

这篇关于带有中文字符的无效URI(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆