2014-11-02 98 views
1

我在代码中收到错误“Illegal character in URL”,我不知道为什么: 我有一个令牌和一个字符串类型的散列。URL中的非法字符

String currentURL = "http://platform.shopyourway.com" + 
        "/products/get-by-tag?tagId=220431" + 
        "&token=" + token + 
        "&hash=" + hash; 
HttpURLConnection urlConnection = null; 
BufferedReader reader = null; 
try { 

    URL url = new URL(currentURL); 
    urlConnection = (HttpURLConnection) url.openConnection(); 
    urlConnection.setRequestMethod("GET"); 
    urlConnection.connect(); 

[...] 

但是当我写道:

URL url = new URL("http://platform.shopyourway.com/products/get-by-tag?tagId=220431&token=0_11800_253402300799_1_a9c1d19702ed3a5e873fd3b3bcae6f8e3f8b845c9686418768291042ad5709f1&hash=e68e41e4ea4ed16f4dbfb32668ed02b080bf1f2cbee64c2692ef510e7f7dc26b"); 

它的工作,但我不能写这个订单,因为我不知道该散列和令牌,因为我生成它们每次。 谢谢。

+5

使用[URLEncoder的](http://stackoverflow.com/questions/10786042/java-url-encoding)上你的值 – Brad 2014-11-02 17:25:47

+1

什么是变量'token'和'hash'? – 2014-11-02 17:26:00

+0

因此,打印哈希的值和令牌的值,并找出哪个字符是非法的。而URE-编码他们,如果你真的很需要那非法字符:http://docs.oracle.com/javase/7/docs/api/java/net/URLEncoder.html – 2014-11-02 17:26:34

回答

2

Oracle docs on creating URLs您需要转义您的URL字符串的“值”。

有特殊字符

一些URL地址URL地址包含特殊字符,例如空格字符 。像这样:

http://example.com/hello world /为了使这些字符合法,它们需要在将它们传递给URL构造函数之前进行编码。

URL url = new URL("http://example.com/hello%20world");

在这个例子中编码特殊字符(S)很容易因为存在需要编码 只有一个字符,但是URL地址是 有几个这样的字符或写作时,如果您不确定 您的代码您需要访问哪些URL地址,可以使用java.net.URI类的多参数构造函数 自动为您编写 编码。

URI uri = new URI("http", "example.com", "/hello world/", "");

然后转换URI到URL。

URL url = uri.toURL();

作为还评论see this other post使用URLEncoder的更换任何违规字符

+1

谢谢URLEncode工作正常 – user1876275 2014-11-02 17:32:57