URISyntaxException - 如何使用%处理网址

时间:2012-09-14 10:00:21

标签: url http-get

我对Java很新,遇到了这个问题。我试过搜索但从未得到正确答案。

我有一个字符串例如

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

现在我需要建立一个带有此String名称的url字符串,如下所示。

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

我尝试用%20替换空格,现在我将新网址改为

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

当我使用这个url并在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);

2 个答案:

答案 0 :(得分:6)

使用%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,但它应该同样有效,两者都可以。

答案 1 :(得分:-1)

您可以使用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);