问题
服务端Controller的入参用@RequestBody接收的Json对象,本地用Post请求访问服务端返回java.io.FileNotFoundException。
确认url正确的情况下,这个异常说明的是入参方式不正确,无法匹配到正确请求地址,出现这种情况的原因很可能是请求参数和接收参数的类型不一致导致,而且注意需要将Post的Content-Type设置为"application/json"。
以下介绍post 提交Json对象请求的正确方法,同时也解决以上出现的问题。
解决方案
服务端Controller内容如下,这里可以用HashMap接收客户端传递过来的JSON对象。
@RequestMapping(value = "/getUserInfo", method = RequestMethod.POST)
@ResponseBody
public ResultMsg getUserInfo(@RequestBody HashMap<String, Object> map) {
String estr = "获取用户档案getUserInfo===:";
ResultMsg rMsg = new ResultMsg();
try {
logger.info(estr + "map:" + map.toString());
return rMsg;
} catch (Exception e) {
logger.error(estr + e.toString());
return rMsg;
}
}
本地Controller内容如下:
import net.sf.json.JSONObject;
// 测试
@RequestMapping("/test")
public String test() {
logger.debug("test ok.");
//创建json对象
String url="http://192.168.0.211:8091/mysev/getUserInfo";
JSONObject jObject = new JSONObject();
jObject.put("arch_no", "00000007");
//转换为json字符串
String jstr = Comm.JsonToStr(jObject);
//以json格式提交post请求
String msg= Comm.httpPost(url,jstr,"application/json");
//输出结果
logger.debug("msg:"+msg.toString());
return "jsp/test";
}
公用方法Comm的内容如下:
/**
* 将JSON对象转成字符串(utf-8)
*
* @param js
* @return
*/
public static String JsonToStr(JSONObject js) {
byte[] bs;
try {
bs = js.toString().getBytes("utf-8");// 编码
String content = new String(bs, "utf-8");
return content;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
/**
* HttpPost请求
* @param vUrl 请求地址
* @param content 参数内容
* @param content_type 报文类型
* @return
*/
public static String httpPost(String vUrl, String content,String content_type) {
try {
URL url = new URL(vUrl);
HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();
httpconn.setRequestProperty("encoding", "UTF-8");// 添加请求属性
if(!content_type.equals(""))
httpconn.setRequestProperty("Content-Type", content_type);
httpconn.setDoInput(true);// 允许输入
httpconn.setDoOutput(true);// 允许输出
httpconn.setRequestMethod("POST");// POST请求 要在获取输入输出流之前设置 否则报错
// 输出
OutputStream os = httpconn.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
BufferedWriter bw = new BufferedWriter(osw);
bw.write(content);
bw.flush();
// 输入
InputStream in = httpconn.getInputStream();
InputStreamReader isr = new InputStreamReader(in, "UTF-8");
BufferedReader br = new BufferedReader(isr);
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
bw.close();
osw.close();
os.close();
br.close();
isr.close();
in.close();
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
本地执行Post请求后,会得到服务端返回的msg消息了。
以上完毕。