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

展开阅读全文

没有更多推荐了,返回首页