Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with the URISyntaxException

Tags:

java

uri

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

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)

I tried : My_Url=My_Url.replace("^","\\^"), but

  1. It won't be the url I need
  2. It doesn't work either

How to handle this ?

Frank

like image 212
Frank Avatar asked Apr 14 '09 23:04

Frank


2 Answers

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.

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");     }   } } 
like image 94
Eddie Avatar answered Sep 18 '22 06:09

Eddie


Use % encoding for the ^ character, viz. http://finance.yahoo.com/q/h?s=%5EIXIC

like image 25
araqnid Avatar answered Sep 19 '22 06:09

araqnid