HTTP POST请求中文乱码问题解决

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/zhangwenlei1404/article/details/75271703

先上代码

public static String sendUrl(String urlString, String pram,String readCharset ) {

StringBuffer sb = new StringBuffer();
DefaultHttpClient httpclient = new DefaultHttpClient();
BufferedReader reader = null;
try{
// 构造最简单的字符串数据    
    StringEntity reqEntity = new StringEntity(pram,"utf-8");
HttpPost httppost = new HttpPost(urlString);  
httppost.addHeader("Content-Type","application/x-www-form-urlencoded; charset=\"UTF-8\"");

// 设置请求的数据    
   httppost.setEntity(reqEntity);
   // 执行
   HttpResponse response = httpclient.execute(httppost);
   HttpEntity entity = response.getEntity();
   
   // 显示结果    
    reader = new BufferedReader(new InputStreamReader(entity.getContent(), readCharset));    
    String line = reader.readLine();    
    while (line  != null) {    
    sb.append(line);
    line = reader.readLine(); 
    }    
    if (entity != null) {    
      entity.consumeContent();    
    }    
        
}catch (Exception e) {
log.error("HttpPostMethodUtil异常",e);
}finally{
try {
if(reader != null){
reader.close();
}
} catch (IOException e) {
log.error("",e);
}
httpclient.getConnectionManager().shutdown();
}
return sb.toString();

}

在网上找的资料说如下两行代码可以解决乱码问题,多次尝试发现并不行。

StringEntity reqEntity = new StringEntity(pram);

reqEntity.setContentEncoding("utf-8");

最后改成如下一行代码,发现解决了中文乱码问题。

StringEntity reqEntity = new StringEntity(pram,"utf-8");


展开阅读全文

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