How to deal with the URISyntaxException

后端 未结 10 2071
攒了一身酷
攒了一身酷 2020-11-28 09:22

I got this error message :

java.net.URISyntaxException: Illegal character in query at index 31: http://finance.yahoo.com/q/h?s=^IXIC

10条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-28 09:46

    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");
        }
      }
    }
    

提交回复
热议问题