编码问题

来源:互联网 发布:unity3d招聘东营 编辑:程序博客网 时间:2024/06/10 06:11


1http调用如果设置编码前后要一致,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(newBasicHeader(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;

}

 

2Base64.encodedecode要成对出现,而且有中文时一定要设置编码。否则会用系统默认编码的!!!!!!!

跨系统时(比如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");

原创粉丝点击