close

  使用URL物件去連一個網址,有時會出現如右的exception: java.net.MalformedURLException: illegal character in url。程式如下:

URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
int status = connection.getResponseCode();   // throw java.net.malformedurlexception

  後來查了urlStr字串,才知道有特殊字元,如換行字元。需借助URLEncoder.encode(urlStr)轉換,例: \n會轉成%0A。而反解碼是URLDecoder.decode。只是沒在connect throw,而在getResponseCode才throw,第一直覺反應不是有特殊字元的問題。

arrow
arrow
    全站熱搜

    Jemmy 發表在 痞客邦 留言(0) 人氣()