Java URISyntaxException 查询中的非法字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18574154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
URISyntaxException Illegal character in query
提问by Harshit Gupta
I am trying to open a link in default browser. I have used the following code.
我正在尝试在默认浏览器中打开一个链接。我使用了以下代码。
String myUrl = "http://www.example.com/engine/myProcessor.jsp?Type=A Type&Name=1100110&Char=!";
try {
Desktop.getDesktop().browse(new URI(myUrl));
} catch (IOException err) {
setTxtOutput("Error: "+err.getMessage());
} catch (URISyntaxException err) {
setTxtOutput("Error: "+err.getMessage());
} catch (Exception err) {
setTxtOutput("Error: "+err.getMessage());
}
I am getting URISyntaxExceptionIllegal character in query at index
我在索引处的查询中收到URISyntaxException非法字符
I think this is because of characters such as ?, &and !in my URL. I tried using:
我认为这是因为诸如? , &和! 在我的网址中。我尝试使用:
URLEncoder.encode(myUrl, "UTF-8");
But this gives me another error.
但这给了我另一个错误。
Failed to open http%3A%2F%2Fwww.example.com%2F...........
The system cannot find the file specified.
Please can you tell me how to correct the URISyntaxException Illegal charactererror.
请您告诉我如何更正URISyntaxException 非法字符错误。
采纳答案by Evgeniy Dorofeev
It's because of the whitespace here ...jsp?Type=A Type&...
, you can replace it with +
这是因为这里有空格...jsp?Type=A Type&...
,您可以将其替换为+
http://www.example.com/engine/myProcessor.jsp?Type=A+Type&Name=1100110&Char=!"
回答by Sotirios Delimanolis
You should not encode the whole URL because the URI class requires a valid protocol. Encode only the parameters
您不应该对整个 URL 进行编码,因为 URI 类需要一个有效的协议。仅对参数进行编码
myUrl = "http://www.example.com/engine/myProcessor.jsp?" + URLEncoder.encode("Type=A Type&Name=1100110&Char=!", "UTF-8");
回答by kkashyap1707
Replace spaces in URL with + like If url contains category=Adult Care then replace it with category=Adult+Care.
将 URL 中的空格替换为 + like 如果 url 包含 category=Adult Care,则将其替换为 category=Adult+Care。
回答by Jorge Santos Neill
The following code work for me:
以下代码对我有用:
MultivaluedMap<String, String> params = new MultivaluedMapImpl();
params.add("filter", URLEncoder.encode(filter));
_webResource.path(MessageFormat.format(this._methodName,this._params))
.queryParams((MultivaluedMap<String, String>) this._params)
.type("application/x-www-form-urlencoded")
.accept("application/json")
.get(ClientResponse.class);
回答by Satish Pawar
You can use following code snippet
您可以使用以下代码片段
public static String encode(String queryParameter) {
try {
String encodedQueryParameter = URLEncoder.encode(queryParameter, "UTF-8");
return encodedQueryParameter;
} catch (UnsupportedEncodingException e) {
return "Issue while encoding" + e.getMessage();
}
}