UrlConnection 请求乱码的解决办法

Posted 魏大宾

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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”);

以上是关于UrlConnection 请求乱码的解决办法的主要内容,如果未能解决你的问题,请参考以下文章

微信开发时遇到的UrlConnection请求乱码的问题

使用httpclient post请求中文乱码解决办法

Java关于中文乱码的解决办法

详解get请求和post请求参数中文乱码的解决办法

get请求和post请求参数中文乱码的解决办法

ajax中文乱码的各种解决办法总结