Java:URI中的非法字符

时间:2012-05-07 20:02:49

标签: java apache http url uri

我尝试使用此源代码

请求googles geo api
client = new DefaultHttpClient();
    HttpGet get=new HttpGet(uri);
        try {
            HttpResponse response = client.execute(get);
            int statusCode = response.getStatusLine().getStatusCode();
             if (statusCode == 200 ){
                    HttpEntity entity = response.getEntity();
                    InputStream is = entity.getContent();
                    try {
                        XMLReader parser = XMLReaderFactory.createXMLReader();
                        parser.setContentHandler(gh);
                        parser.parse(new InputSource(is));
                    } catch (IllegalStateException e) {
                        e.printStackTrace();
                    } catch (SAXException e) {
                        e.printStackTrace();
                    }
             }
        } catch (IOException e) {
            e.printStackTrace();
        }

URI是这样的吗? http://maps.googleapis.com:80/maps/api/geocode/xml?address =Königstraße,Berlin& sensor = false

抛出异常:非法角色!

我怎样才能逃脱ä,ü,ö,ß和空白? 我尝试使用ISO-8859-1作为编码的java.net.URLEncoder而没有成功:(

尊重igor

2 个答案:

答案 0 :(得分:5)

您需要使用UTF-8对单个请求参数值进行URL编码,而不是使用ISO-8859-1对整个URL进行URL编码。

String url = "http://maps.googleapis.com:80/maps/api/geocode/xml"
    + "?address=" + URLEncoder.encode("Königstraße, Berlin", "UTF-8") 
    + "&sensor=false";

答案 1 :(得分:0)

K%C3%B6nigstra%C3%9Fe UTF-8百分比编码也可以。

相关问题