本篇博客试用于编写java后台接口以及两个项目之间的接口对接功能;
具体的内容如下:
1.java后台给指定接口发送json数据
package com.utils; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import net.sf.json.JSONObject; public class testOne { public static void main(String[] args) { JSONObject jsobj1 = new JSONObject(); JSONObject jsobj2 = new JSONObject(); jsobj2.put("deviceID", "112"); jsobj2.put("channel", "channel"); jsobj2.put("state", "0"); jsobj1.put("item", jsobj2); jsobj1.put("requestCommand", "control"); post(jsobj1,"http://192.168.3.4:8080/HSDC/test/authentication"); } public static String post(JSONObject json,String path) { String result=""; try { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 使用 URL 连接进行输出,则将 DoOutput标志设置为 true conn.setDoOutput(true); conn.setRequestMethod("POST"); OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); // 向服务端发送key = value对 out.write(json.toString()); out.flush(); out.close(); // 如果请求响应码是200,则表示成功 System.out.println("conn=="+conn); if (conn.getResponseCode() == 200) { // HTTP服务端返回的编码是UTF-8,故必须设置为UTF-8,保持编码统一,否则会出现中文乱码 BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); System.out.println("in ==="+in ); result = in.readLine(); in.close(); } conn.disconnect();// 断开连接 } catch (Exception e) { System.out.println("请求异常"); throw new RuntimeException(e); } System.out.println("result=="+result); return result; } }
2.java后台接收json数据
package com.controller; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("test") public class TestConttroller extends BaseController{ @RequestMapping(value="authentication",produces = MediaType.APPLICATION_JSON_VALUE,method = RequestMethod.POST) public Map<String,Object> getString() throws UnsupportedEncodingException, IOException{ System.out.println("进入====================="); //后台接收 InputStreamReader reader=new InputStreamReader(request.getInputStream(),"UTF-8"); char [] buff=new char[1024]; int length=0; while((length=reader.read(buff))!=-1){ String x=new String(buff,0,length); System.out.println(x); } //响应 Map<String,Object> jsonObject = new HashMap<String, Object>(); //创建Json对象 jsonObject.put("username", "张三"); //设置Json对象的属性 jsonObject.put("password", "123456"); return jsonObject; } }
运行testOne之后将json数据发送到authentication接口,接收的数据如图:
testOne中main方法返回的数据如图:
至此java后台发送及接收json数据代码也就完成了,希望帮助到你。记得给赞哦!!!