URISyntaxException-如何使用%处理网址 [英] URISyntaxException - How to deal with urls with %

查看:181
本文介绍了URISyntaxException-如何使用%处理网址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Java还是很陌生,并且遇到了这个问题.我尝试搜索,但是没有得到正确的答案.

I am fairly new to Java and came across this issue. I tried searching but never got a correct answer.

我有一个字符串,例如

String name = anything 10%-20% 04-03-07

现在,我需要使用如下所示的String名称构建一个url字符串.

Now I need to build up a url string with this String name like below.

http://something.com/test/anything 10%-20% 04-03-07

我尝试用%20替换空格,现在我得到的新网址为

I tried replacing the spaces with %20 and now I am getting the new url as

http://something.com/test/anything%2010%-20%%2004-03-07

当我使用此URL并将其在firefox中启动时,它可以正常工作,但是在Java中处理时,显然会抛出

When I use this url and fire it in firefox it just works fine but while processing in Java it is apparently throwing

Exception in thread "main" java.lang.IllegalArgumentException
at java.net.URI.create(Unknown Source)
at org.apache.http.client.methods.HttpGet.<init>(HttpGet.java:69)
Caused by: java.net.URISyntaxException: Malformed escape pair at index 39 : 
at java.net.URI$Parser.fail(Unknown Source)
at java.net.URI$Parser.scanEscape(Unknown Source)
at java.net.URI$Parser.scan(Unknown Source)
at java.net.URI$Parser.checkChars(Unknown Source)
at java.net.URI$Parser.parseHierarchical(Unknown Source)
at java.net.URI$Parser.parse(Unknown Source)
at java.net.URI.<init>(Unknown Source)
... 6 more

这是代码抛出错误

HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);

推荐答案

还用%25编码百分号.

http://something.com/test/anything 10%-20% 04-03-07将与http://something.com/test/anything%2010%25-20%25%2004-03-07一起使用.

例如,您应该可以使用

You should be able to use for example URLEncoder.encode for this - just remember, that you need to urlencode the path part, not anything before that, so something like

String encodedUrl =
    String.format("http://something.com/%s/%s",
      URLEncoder.encode("test", "UTF-8"),
      URLEncoder.encode("anything 10%-20% 04-03-07", "UTF-8")
    );

注意:URLEncoder将空格编码为+而不是%20,但是它应该同样有效,两者都可以.

Note: URLEncoder encodes spaces to + instead of %20, but it should work equally well, both are ok.

这篇关于URISyntaxException-如何使用%处理网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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