HttpURLConnection 请求

咱们常常在程序中发送Web请求,可是也常常在请求中出现乱码问题。下面的代码是发送请求的通用方法,可是在某些环境下中文会乱码,如何解决乱码问题呢?一开始的时候,我只想到对传入的参数进行html

URLEncoder.encode(params.get("title"),"UTF-8");java

而后在服务端发现接收的数据仍是乱码,根本不用解码已经乱了,后面高人指点以下:json

URLEncoder.encode(URLEncoder.encode(params.get("title"),"UTF-8"),"UTF-8");服务器

而后在服务器端以下:网络

URLDecoder.decode(jsonvalue.get("title").toString(),"UTF-8");app

终于获得了想要的中文。ide

总结:网络传输时,数据会被解析两次,第一次是在网络中,第二次是在服务器。若是咱们在传输网络数据的时候没有加码,那么会解析为乱码,因此咱们避免中文乱码,须要加码两次,第一次是让网络解析,解析事后仍是加码的全部不会乱码,到服务器在解码问题就解决了。post


 /**
  * 客户端发送HTTP请求通用POST方法
  * @param url
  * @param params
  * @return
  * @throws Exception
  */
 public static String postHttpRequest(String url , Map<String,String> params)throws Exception{
  // 对空URL不处理
  if(url == null || url.length() == 0) return null;
 
  String result = null;
  // 处理参数
  String param = encodeUrlParams(params);
  if(param != null && param.length() > 0){
   if(url.contains("?")){
    url = url + "&" + param;
   }else{
    url = url + "?" + param;
   }
  }
  URL console = new URL(url);  
  HttpURLConnection conn = (HttpURLConnection)console.openConnection();  
  conn.setConnectTimeout(3000);//追加一个超时设置:3秒
  conn.setRequestMethod("POST");// POST请求  
  conn.setRequestProperty("Content-type", "text/html");
  conn.setRequestProperty("Accept-Charset", "utf-8");
  conn.setRequestProperty("contentType", "utf-8");
  // 开始链接
  conn.connect();
  InputStream is = conn.getInputStream();
  BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF8"));
  StringBuffer sb = new StringBuffer();
 
  String curLine="";
  while ((curLine = reader.readLine()) != null) {
   sb.append(curLine);
  }
  is.close();
 
  result = sb.toString();
 
  return result;  
 }
 
 
 /**
  * 处理参数
  * @param param
  * @return
  * @throws UnsupportedEncodingException
  */
 private static String encodeUrlParams(Map<String,String> param) throws UnsupportedEncodingException{
  StringBuilder bulider = new StringBuilder();
  if(param != null){
   Set<String> keys = param.keySet();
   for(String key : keys){
    if(StringUtils.isBlank(param.get(key))){
     bulider.append(key).append("=").append("").append("&");
    }else{
     bulider.append(key).append("=").append(param.get(key)).append("&");
    }
   }
  }
  if(bulider.length() > 0){
   return bulider.substring(0, bulider.length()-1);
  }
  return bulider.toString();
 }
 
}
相关文章
相关标签/搜索