android Post ,后台SpringMVC接收

1.Post的是Form格式,即key1=value1&key2=value2,可以request.getParameter(key)接受

2.Post的是Json,request.getParameter(key)会是空值,改用@RequestBody接收,类型看客户端,例如Map、List


例子:

客户端android post主要代码:

Gson gson = new Gson();
// Object轉JSON
String json = gson.toJson(JSONmap);
byte[] jsonbytes = json.getBytes();
// 設置發送數據長度
httpURLConnection.setRequestProperty("Content-Length", String.valueOf(jsonbytes.length));
OutputStream outwritestream;
try {
    outwritestream = httpURLConnection.getOutputStream();
    outwritestream.write(jsonbytes);
    outwritestream.flush();
    outwritestream.close();
} catch (IOException e) {
    e.printStackTrace();
}

服务端代码:

@ResponseBody
@RequestMapping(value = "/android/post", method = { RequestMethod.POST })
public Map androidPost(@RequestBody Map pData,HttpServletRequest request, HttpServletResponse response) {
	Map map = new HashMap();
	 try {
		BufferedReader bufferedReader= request.getReader();
		String body, temp = "";
		while((temp = bufferedReader.readLine()) != null){
		body += temp;
		}
		logger.info(body);
	} catch (IOException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}
	return map;
}
以上代码抛出异常,原因是

@RequestBody Map pData

导致request.getReader()异常,注释掉,打印出的是JSON

再修改代码:

@ResponseBody
@RequestMapping(value = "/android/post", method = { RequestMethod.POST })
public Map androidPost(@RequestBody Map pData,HttpServletRequest request, HttpServletResponse response) {
	Map map = new HashMap();
	logger.info(pData.toString());
	return map;
}

同样是JSON

测试到这里结束,以上只是关键代码,android端上还有一种拼接KEY=VALUE的方式,感觉有点繁琐,这里就不贴了。

如有错误请指点,本人也是新手一枚。

你可能感兴趣的:(Java)