1、http调用如果设置编码前后要一致,httppost请求设置编码要和收到请求后解析时的编码保持一致。
//发送请求时
public static voidjsonProcess(JSONObject json,String uri) throws ClientProtocolException,IOException{
HttpPostpost = new HttpPost(uri);
post.addHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8");
StringEntityse = new StringEntity(json.toJSONString(), "UTF-8");
se.setContentType("text/json;charset=UTF-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
post.setEntity(se);
HttpResponseresponse = new DefaultHttpClient().execute(post);
System.out.println(EntityUtils.toString(response.getEntity()));
}
//收到请求后解析时设置编码
privateString _getInputString(HttpServletRequest request)
throwsUnsupportedEncodingException, IOException {
InputStreaminputStream = request.getInputStream();
Stringcharset = request.getCharacterEncoding();
if(charset == null || charset.isEmpty()) {
charset= "UTF-8";
}
StringrequestStr = StreamUtil.readStreamToString(inputStream, charset);
returnrequestStr;
}
2、Base64.encode和decode要成对出现,而且有中文时一定要设置编码。否则会用系统默认编码的!!!!!!!
跨系统时(比如windows请求到linux系统时,会发生乱码问题)
在字符串转为字节数组时,最好指定编码。(否则会用系统默认编码或者容器编码???)
加密的时候先将字符串转为byte[],再对bytes进行Base64.encode
byte[] bytes = postXml.getBytes("UTF-8")
StringuserPlainBase64Text = new String(Base64.encode(bytes ));
在字节数组转为字符串时,也要指定编码。(否则会用系统默认编码或者容器编码???)
解密的时候先对密文进行Base64.decode,再将bytes转为字符串。
byte[] bytes = Base64.decode(userSourceBase64Text);
StringuserSourceText = new String( bytes ,"UTF-8");