1. 程式人生 > >UrlConnection 請求亂碼的解決辦法

UrlConnection 請求亂碼的解決辦法

原先的程式碼如下:


public class GetMessage
{
  private static final String v_url = "";

  public static String getPostInfo(String v_methodname, String v_urlparam)    throws IOException
  {
    PrintWriter out = null;
    BufferedReader in = null;
    String result = "";
    URL url = new URL(v_url + v_methodname);
    URLConnection conn = url.openConnection();
    conn.setRequestProperty("accept"
, "*/*"); conn.setRequestProperty("Accept-Charset", "UTF-8"); conn.setRequestProperty("contentType", "UTF-8"); conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset=UTF-8"); conn.setRequestProperty("Accept-Language", Locale.getDefault().toString()); conn.setRequestProperty( "Accept"
, "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*"); conn.setConnectTimeout(5000); conn.setReadTimeout(5000
); conn.setDoOutput(true); //String encoding = System.getProperty("file.encoding"); out = new PrintWriter(conn.getOutputStream()); out.print(v_urlparam); out.flush(); out.close(); result = readStrByCode(conn.getInputStream(), "UTF-8"); return result; } public static String readStrByCode(InputStream is, String code) { StringBuilder builder = new StringBuilder(); BufferedReader reader = null; String line=""; try { reader = new BufferedReader(new InputStreamReader(is, code)); while ((line = reader.readLine()) != null) { builder.append(line); } } catch (Exception e) { e.printStackTrace(); try { reader.close(); } catch (IOException e1) { e1.printStackTrace(); } } finally { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } return builder.toString(); } }

這個在UFT-8專案裡面呼叫沒有問題,其他編碼的呼叫就會出現亂碼。經發現是這句程式碼引起字符集的變化
out = new PrintWriter(conn.getOutputStream()); 如果專案不是UTF-8就會轉成當前環境的編碼,修改成如下方式就解決問題了。

    OutputStreamWriter out = new OutputStreamWriter(conn  
            .getOutputStream(), "UTF-8"); 
    out.write(v_urlparam); 

如果涉及到對欄位加密,需要將需要加密的字元先轉成UFT-8的編碼格式即:v_userid = new String(v_userid.toString().getBytes(“iso8859-1”), “utf-8”);