如何处理URISyntaxException

Fra*_*ank 40 java uri

我收到此错误消息:

java.net.URISyntaxException: Illegal character in query at index 31: http://finance.yahoo.com/q/h?s=^IXIC
Run Code Online (Sandbox Code Playgroud)

My_Url = http://finance.yahoo.com/q/h?s=^IXIC

当我将它复制到浏览器地址字段时,它显示正确的页面,它是有效的URL,但我不能解析它:new URI(My_Url)

我试过了My_Url=My_Url.replace("^","\\^"),但是

  1. 它不会是我需要的网址
  2. 它也不起作用

怎么办呢?

坦率

Edd*_*die 57

您需要对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");
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 要在任何 # 锚点或非默认端口之后保留内容,请执行以下操作:URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); (2认同)

ara*_*nid 18

%^字符使用编码,即.http://finance.yahoo.com/q/h?s=%5EIXIC


Osc*_*Ryz 15

您必须对参数进行编码.

这样的事情会做:

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

    }
}
Run Code Online (Sandbox Code Playgroud)

http://java.sun.com/javase/6/docs/api/java/net/URLEncoder.html