的URISyntaxException - 如何处理与%网址(URISyntaxException

2019-09-22 10:24发布

我是相当新的Java和碰到这个问题。 我试图寻找,但一直没有得到正确的答案。

我的字符串,例如

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

现在我需要建立一个URL字符串中包含此字符串名称。

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

我试着用20%替代空间,现在我得到了新网址

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

当我使用这个网址,并在Firefox启动它,它只是正常工作,但同时在Java中处理这显然是投掷

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);

Answer 1:

也编码与百分号%25

http://something.com/test/anything 10%-20% 04-03-07将与合作http://something.com/test/anything%2010%25-20%25%2004-03-07

您应该能够使用例如URLEncoder.encode对于这一点-只要记住,你需要来urlencode路径部分,在此之前没有任何东西,所以像

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 ,但它应该工作一样好,都是好的。



Answer 2:

你可以使用java.net.URI中的从您的字符串创建URI

String url = "http://something.com/test/anything 10%-20% 04-03-07"

URI uri = new URI(
    url,
    null);
String request = uri.toASCIIString();

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


文章来源: URISyntaxException - How to deal with urls with %
标签: url http-get