7

我对Java相当陌生,遇到了这个问题。我尝试搜索,但从未得到正确答案。

例如,我有一个字符串

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

现在我需要用这个字符串名称构建一个 url 字符串,如下所示。

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

我尝试用 %20 替换空格,现在我得到了新的 url

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

2 回答 2

8

还用 编码百分号%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,但它应该同样有效,两者都可以。

于 2012-09-14T10:04:29.497 回答
0

您可以使用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);
于 2012-09-14T10:09:20.877 回答