java url處理常遇到的問題

1、通過HttpURLConnection得到的數據中文亂碼

urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod(method);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
        urlConnection.setConnectTimeout(defaultTimeout);
urlConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
urlConnection.setRequestProperty("Content-Type", "text/plain;charset=UTF-8");

        設置一下Content-Type,然後用下面的方式接收數據:

        InputStream in = urlConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));

2、URLDecoder.decode(line, "UTF-8") 遇到如下異常

      java.lang.IllegalArgumentException: URLDecoder: Illegal hex characters in escape (%) pattern - For input string: "+%"

主要原因是% 在URL中是特殊字符,需要特殊轉義一下,使用%25替換字符串中的%號,如下:

 line = line.replaceAll("%(?![0-9a-fA-F]{2})", "%25");

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章