How to deal with the URISyntaxException

后端 未结 10 2083
攒了一身酷
攒了一身酷 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:45

    I had this exception in the case of a test for checking some actual accessed URLs by users.

    And the URLs are sometime contains an illegal-character and hang by this error.

    So I make a function to encode only the characters in the URL string like this.

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

提交回复
热议问题