最近在写一个电商平台的项目,原本任务已经完成,但是淘宝做妖,限制数据输出,只能通过奇门的方式获取订单数据,故又多了一个模块任务。
通过奇门推数据的时候,你要获得推过来的数据,传统的方式是通过参数名获取其值,但是有个问题,这个时候你不知道奇门传过来的参数名是什么,而且数据是以xml的格式传过来的,故传统参数形式不行,想了很久,考虑用输入流的方式来获取数据;
主要思路:
1,获取输入流
2,将输入流转为字符串
3,解码
@RequestMapping(value = "/getTradeList", method = RequestMethod.POST )
@ResponseBody
public String getTradeList(HttpServletRequest req ) throws IOException {
req.setCharacterEncoding("UTF-8");
String tradeInfos = "";
try {
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(req.getInputStream(),"utf-8")); //读取参数流
String nextLine = bufferedReader.readLine();
while( nextLine != null )
{
System.out.println(req.getCharacterEncoding());
tradeInfos += nextLine;
nextLine = bufferedReader.readLine();
}
tradeInfos =URLDecoder.decode(tradeInfos, "UTF-8");//解码
System.out.println(tradeInfos);
//让浏览器用utf8来解析返回的数据
response.setHeader("Content-type", "text/html;charset=UTF-8");
//告诉servlet用UTF-8转码,而不是用默认的ISO-8859-1
response.setCharacterEncoding("UTF-8");
String data = "中国";
PrintWriter pw = response.getWriter();
pw.write(data+tradeInfos); //这样将数据返回到了前端,且不会乱码
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
http中文乱码问题: http://www.sojson.com/blog/227.html
servlet后台返回及乱码问题:http://blog.csdn.net/qq_36523667/article/details/78585229