在BAE平台上getWriter(),getOutputStream()返回JSON中文乱码问题

最近打算写一个简单的javaweb程序放到BAE3.0上来响应android的请求,多线程读取网络上的json数据然后解析出有用的数据在合并成新的json对象。

结果服务器返回json对象时发现其中的中文变成了乱码了都是????。

设置response.setContentType("text/json;charset=UTF-8");或者

response.setContentType("text/json");
response.setCharacterEncoding("UTF-8");

都还是输出的中文显示乱码。经过调试发现是读取网络上的json时就是乱码了。

把代码js = new String(baos.toByteArray());修改成js = baos.toString("UTF-8");读取的json就能正常显示中文了。

// 根据传进来的网址读取JSON
public String getJsonString(String path) {
	String js = "";
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	// 建立一个byte数组作为缓冲区,等下把读取到的数据储存在这个数组
	try {
		byte[] buffer = new byte[1024];
		int len = 0;
		URL url = new URL(path);
		HttpURLConnection huc = (HttpURLConnection) url.openConnection();
		huc.setRequestMethod("GET");
		huc.setReadTimeout(6000);
		huc.setConnectTimeout(3500);
		InputStream ips = huc.getInputStream();
		while ((len = ips.read(buffer)) != -1) {
			baos.write(buffer, 0, len);
		}
		js = baos.toString("UTF-8");
		baos.close();
	} catch (ProtocolException e) {
		e.printStackTrace();
	} catch (MalformedURLException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	return js;
}

结果返回数据的时候发现用response.getWriter().write(getJsonString(match_id));返回的数据里中文还是显示乱码.

但是修改成response.getWriter().print(getJsonString(match_id));以后就正常显示中文了。

查了下发现print方法会自动的把字符转换成字节,用的编码是平台的默认编码。

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/json");
		response.setCharacterEncoding("UTF-8");
		String number = request.getParameter("number");
		if (match_id != null && !match_id.isEmpty()) {
			//response.getWriter().write(getJsonString(match_id));
			response.getWriter().print(getJsonString(match_id));
	        }
}

如果是选择字节流输出则用:response.getOutputStream().write(getJsonString(match_id));

或者response.getOutputStream().print(getJsonString(match_id).getBytes("UTF-8"));都能正常显示中文。

原文地址:https://www.cnblogs.com/zhengxt/p/3492920.html