http交互乱码

本文介绍了解决HTTP请求及响应中出现中文乱码的方法。针对请求乱码问题,通过自定义PostMethod类设置请求字符集为UTF-8。对于响应乱码,则需在服务器端设置正确的字符集及Content-Type头信息。

请求乱码

import org.apache.commons.httpclient.methods.PostMethod;

public class HebabyPost extends PostMethod{
    public HebabyPost(String url) {
        super(url);
    }

    @Override
    public String getRequestCharSet() {
        return "UTF-8";
    }
}

 

响应乱码

 

经验:1,如果中文返回出现??字符,这表明没有加response.setCharacterEncoding("UTF-8");这句话。

            2,如果返回的中文是“烇湫”这种乱码,说明浏览器的解析问题,应该检查下是否忘加response.setHeader("Content-type", "text/html;charset=UTF-8");这句话。

 

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		InputStream requestInputStream = request.getInputStream();
        String requestJson = IOUtils.toString(requestInputStream, "UTF-8");
        System.out.println("HttpServer.doPost requestJson:[" + requestJson + "]");
        response.setHeader("Content-type", "application/json;charset=UTF-8");  
		response.setCharacterEncoding("UTF-8");
		//String result = "{\"error_code\":0,\"return_code\":1,\"error_msg\":\"添加成功\"}";
		String result = "lBpZgm5bnZQRnYZFbHzi+mkkR0Wtg026OixCWAnR0vtxk5F4NXOoZYdrvRa2 72P6h6L8lOG07Ug=";
		response.getWriter().append(result);
	}

 

转载于:https://my.oschina.net/yizhichao/blog/1549185

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值