编码问题



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(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;

}

 

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");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值