使用HttpURLConnection创建连接
public static void leankReturnJsonTest (){
HttpURLConnection conn = null;try {
// 创建一个URL对象
URL url = new URL("http://127.0.0.1:8080/soc/infoMonitor/leankReturnJsonTest");
// 调用URL的openConnection()方法,获取HttpURLConnection对象
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");// 设置请求方法为post
conn.setReadTimeout(5000);// 设置读取超时为5秒
conn.setConnectTimeout(10000);// 设置连接网络超时为10秒
conn.setDoOutput(true);// 设置此方法,允许向服务器输出内容
// post请求的参数
String data = "message=" + jsonMethod();
// 获得一个输出流,向服务器写数据,默认情况下,系统不允许向服务器输出内容
OutputStream out = conn.getOutputStream();// 获得一个输出流,向服务器写数据
out.write(data.getBytes());
out.flush();
out.close();
int responseCode = conn.getResponseCode();// 调用此方法就不必再使用conn.connect()方法
if (responseCode == 200) {
InputStream is = conn.getInputStream();
String state = getStringFromInputStream(is);
System.out.println(state);
} else {
System.out.println("shibai");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();// 关闭连接
}
}
}
// 产生json数据方法,使用的是阿里巴巴的fastjson工具包
public static String jsonMethod(){
JSONObject jsonObject = new JSONObject();
jsonObject.put("leanknumber", "23");
jsonObject.put("contact", "fsdfsdf");
jsonObject.put("contactinfo","cdf");
jsonObject.put("dealdetail","qilai a ");
jsonObject.put("unit","unitv");
jsonObject.put("department","department");
String jsonstr = JSONObject.toJSONString(jsonObject);
System.out.println(jsonstr);
return jsonstr;
}
springmvc端接收数据方式,同样使用fastjson解析数据
//produces = "application/xml; charset=utf-8" ,用来控制返回数据的格式和编码
@SuppressWarnings("deprecation")
@RequestMapping(value="/leankReturnJsonTest" , method=RequestMethod.POST , produces = "application/json; charset=utf-8")
public @ResponseBody String leankReturnTest(String message) throws IOException{
JSONObject jsonObject = (JSONObject) JSONObject.parse(message);
System.out.println(jsonObject.get("leanknumber"));
JSONObject jsonReturn = new JSONObject();
jsonReturn.put("replyId", "12312");
jsonReturn.put("state", "success");
return jsonReturn.toJSONString();
}