HttpClient Post/GetMethod 转码方案汇总

HttpClient Post  方式模拟请求时常会遇到中文转码问题,这里我总结一下本身遇到的几种状况和解决方案。html

一、请求网页java

GetMethod getMethod = new GetMethod("http://www.baidu.com");  
//(1)、这里能够设置本身想要的编码格式
getMethod.getParams().setContentCharset("GB2312"); 

//(2)、对于get方法也能够这样设置 
getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"GB2312");  

//(3)、还能够以下这样设置
getMethod.addRequestHeader("Content-Type", "text/html; charset=UTF-8");  
 
//(4)、固然一样能够直接设置 httpClient 对象的编码格式
HttpClient httpClient = new HttpClient();
httpClient.getParams().setContentCharset("GB2312");

//使用流的方式读取也能够以下设置
InputStream in = getMethod.getResponseBodyAsStream();  
//这里的编码规则要与上面的相对应  
BufferedReader br = new BufferedReader(new InputStreamReader(in,"GB2312"));

二、请求方法ide

PostMethod PostMethod= new PostMethod("http://localhost:8080/ezid-cert-mobile/upload");
//(1)、一般能够以下设置本身想要的编码格式
postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");

//(2)、也重载PostMethod的getRequestCharSet()方法
public  class UTF8PostMethod extends PostMethod{
    public UTF8PostMethod(String url){
        super(url);
    }
    @Override
    public String getRequestCharSet() {
     return "UTF-8";
    }
}

//(3)、若是是方法的参数出现乱码问题,那么你能够以下设置参数
Charset utf8Charset = Charset.forName("UTF-8");
multipartContent.addPart("name", new StringBody(Info.getUserEntity().getName(), utf8Charset));

//(4)、若是你用的是Part [] parts={...}传参方式的话能够以下设置
StringPart name=new StringPart("name",certFormEntity.getPersonName(), "UTF-8");
相关文章
相关标签/搜索