Java 如何处理URISyntaxException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/749709/
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
How to deal with the URISyntaxException
提问by Frank
I got this error message :
我收到此错误消息:
java.net.URISyntaxException: Illegal character in query at index 31: http://finance.yahoo.com/q/h?s=^IXIC
My_Url = http://finance.yahoo.com/q/h?s=^IXIC
My_Url = http://finance.yahoo.com/q/h?s=^IXIC
When I copied it into a browser address field, it showed the correct page, it's a valid URL
, but I can't parse it with this: new URI(My_Url)
当我将它复制到浏览器地址字段时,它显示了正确的页面,它是一个有效的URL
,但我无法用这个解析它:new URI(My_Url)
I tried : My_Url=My_Url.replace("^","\\^")
, but
我试过:My_Url=My_Url.replace("^","\\^")
,但是
- It won't be the url I need
- It doesn't work either
- 它不会是我需要的网址
- 它也不起作用
How to handle this ?
如何处理?
Frank
坦率
采纳答案by araqnid
Use %
encoding for the ^
character, viz. http://finance.yahoo.com/q/h?s=%5EIXIC
%
对^
字符使用编码,即。http://finance.yahoo.com/q/h?s=%5EIXIC
回答by Eddie
You need to encode the URI to replace illegal characters with legal encoded characters. If you first make a URL (so you don't have to do the parsing yourself) and then make a URI using the five-argument constructor, then the constructor will do the encoding for you.
您需要对 URI 进行编码以将非法字符替换为合法的编码字符。如果您首先创建一个 URL(因此您不必自己进行解析),然后使用五参数构造函数创建一个 URI ,那么构造函数将为您进行编码。
import java.net.*;
public class Test {
public static void main(String[] args) {
String myURL = "http://finance.yahoo.com/q/h?s=^IXIC";
try {
URL url = new URL(myURL);
String nullFragment = null;
URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), nullFragment);
System.out.println("URI " + uri.toString() + " is OK");
} catch (MalformedURLException e) {
System.out.println("URL " + myURL + " is a malformed URL");
} catch (URISyntaxException e) {
System.out.println("URI " + myURL + " is a malformed URL");
}
}
}
回答by OscarRyz
You have to encode your parameters.
您必须对参数进行编码。
Something like this will do:
像这样的事情会做:
import java.net.*;
import java.io.*;
public class EncodeParameter {
public static void main( String [] args ) throws URISyntaxException ,
UnsupportedEncodingException {
String myQuery = "^IXIC";
URI uri = new URI( String.format(
"http://finance.yahoo.com/q/h?s=%s",
URLEncoder.encode( myQuery , "UTF8" ) ) );
System.out.println( uri );
}
}
http://java.sun.com/javase/6/docs/api/java/net/URLEncoder.html
http://java.sun.com/javase/6/docs/api/java/net/URLEncoder.html
回答by Grigory Kislin
Coudn't imagine nothing better for
http://server.ru:8080/template/get?type=mail&format=html&key=ecm_task_assignment&label=Согласовать с контрагентом&descr=Описание&objectid=2231
that:
无法想象没有比
http://server.ru:8080/template/get?type=mail&format=html&key=ecm_task_assignment&label=Согласовать с контрагентом&descr=Описание&objectid=2231
更好的了
:
public static boolean checkForExternal(String str) {
int length = str.length();
for (int i = 0; i < length; i++) {
if (str.charAt(i) > 0x7F) {
return true;
}
}
return false;
}
private static final Pattern COLON = Pattern.compile("%3A", Pattern.LITERAL);
private static final Pattern SLASH = Pattern.compile("%2F", Pattern.LITERAL);
private static final Pattern QUEST_MARK = Pattern.compile("%3F", Pattern.LITERAL);
private static final Pattern EQUAL = Pattern.compile("%3D", Pattern.LITERAL);
private static final Pattern AMP = Pattern.compile("%26", Pattern.LITERAL);
public static String encodeUrl(String url) {
if (checkForExternal(url)) {
try {
String value = URLEncoder.encode(url, "UTF-8");
value = COLON.matcher(value).replaceAll(":");
value = SLASH.matcher(value).replaceAll("/");
value = QUEST_MARK.matcher(value).replaceAll("?");
value = EQUAL.matcher(value).replaceAll("=");
return AMP.matcher(value).replaceAll("&");
} catch (UnsupportedEncodingException e) {
throw LOGGER.getIllegalStateException(e);
}
} else {
return url;
}
}
回答by smola
A general solution requires parsing the URL into a RFC 2396 compliant URI (note that this is an old version of the URI standard, which java.net.URI uses).
通用解决方案需要将 URL 解析为符合 RFC 2396 的 URI(请注意,这是 URI 标准的旧版本,java.net.URI 使用该标准)。
I have written a Java URL parsing library that makes this possible: galimatias. With this library, you can achieve your desired behaviour with this code:
我编写了一个 Java URL 解析库,使这成为可能:galimatias。使用此库,您可以使用以下代码实现所需的行为:
String urlString = //...
URLParsingSettings settings = URLParsingSettings.create()
.withStandard(URLParsingSettings.Standard.RFC_2396);
URL url = URL.parse(settings, urlString);
Note that galimatias is in a very early stage and some features are experimental, but it is already quite solid for this use case.
请注意,galimatias 还处于非常早期的阶段,一些功能还处于试验阶段,但对于这个用例来说已经非常可靠了。
回答by Ayabe Hidetoshi
I had this exception in the case of a test for checking some actual accessed URLs by users.
在检查用户实际访问的 URL 的测试中,我遇到了这个异常。
And the URLs are sometime contains an illegal-character and hang by this error.
并且 URL 有时包含非法字符并因此错误而挂起。
So I make a function to encode only the characters in the URL string like this.
所以我制作了一个函数来像这样只对 URL 字符串中的字符进行编码。
String encodeIllegalChar(String uriStr,String enc)
throws URISyntaxException,UnsupportedEncodingException {
String _uriStr = uriStr;
int retryCount = 17;
while(true){
try{
new URI(_uriStr);
break;
}catch(URISyntaxException e){
String reason = e.getReason();
if(reason == null ||
!(
reason.contains("in path") ||
reason.contains("in query") ||
reason.contains("in fragment")
)
){
throw e;
}
if(0 > retryCount--){
throw e;
}
String input = e.getInput();
int idx = e.getIndex();
String illChar = String.valueOf(input.charAt(idx));
_uriStr = input.replace(illChar,URLEncoder.encode(illChar,enc));
}
}
return _uriStr;
}
test:
测试:
String q = "\'|&`^\"<>)(}{][";
String url = "http://test.com/?q=" + q + "#" + q;
String eic = encodeIllegalChar(url,'UTF-8');
System.out.println(String.format(" original:%s",url));
System.out.println(String.format(" encoded:%s",eic));
System.out.println(String.format(" uri-obj:%s",new URI(eic)));
System.out.println(String.format("re-decoded:%s",URLDecoder.decode(eic)));
回答by Wil Hester
Rather that encoding the URL before hand you can do the following
而不是事先对 URL 进行编码,您可以执行以下操作
String link = "http://foo.com";
URL url = null;
URI uri = null;
try {
url = new URL(link);
} catch(MalformedURLException e) {
e.printStackTrace();
}
try{
uri = new URI(url.toString)
} catch(URISyntaxException e {
try {
uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(),
url.getPort(), url.getPath(), url.getQuery(),
url.getRef());
} catch(URISyntaxException e1 {
e1.printStackTrace();
}
}
try {
url = uri.toURL()
} catch(MalfomedURLException e) {
e.printStackTrace();
}
String encodedLink = url.toString();
回答by gary69
If you're using RestangularV2
to post to a spring controller in java you can get this exception if you use RestangularV2.one()
instead of RestangularV2.all()
如果您使用RestangularV2
在 java 中发布到 spring 控制器,如果您使用RestangularV2.one()
而不是RestangularV2.all()
回答by kkashyap1707
Replace spaces in URL with + like If url contains dimension1=Incontinence Liners then replace it with dimension1=Incontinence+Liners.
将 URL 中的空格替换为 + like 如果 url 包含维度 1=失禁衬垫,则将其替换为维度 1=失禁+衬垫。
回答by Jebil
A space is encoded to %20 in URLs, and to + in forms submitted data (content type application/x-www-form-urlencoded). You need the former.
空格在 URL 中编码为 %20,在表单提交的数据中编码为 +(内容类型 application/x-www-form-urlencoded)。你需要前者。
Using Guava:
使用番石榴:
dependencies {
compile 'com.google.guava:guava:28.1-jre'
}
You can use UrlEscapers:
您可以使用 UrlEscapers:
String encodedString = UrlEscapers.urlFragmentEscaper().escape(inputString);
Don't use String.replace, this would only encode the space. Use a library instead.
不要使用 String.replace,这只会对空间进行编码。改用图书馆。