Java⽤HTTP的⽅式发送JSON报⽂请求
前⾔:
项⽬调⽤第三⽅接⼝时,通常是⽤socket或者http的通讯⽅式发送请求:http 为短连接,客户端发送请求都需要服务器端回送响应,请求结束后,主动释放链接。Socket为长连接:通常情况下Socket 连接就是 TCP 连接,因此 Socket 连接⼀旦建⽴,通讯双⽅开始互发数据内容,直到双⽅断开连接。下⾯介绍HTTP的⽅式发送和接收JSON报⽂。
socket通信报文格式需求:
⽤HTTP的⽅式,向URL为10.10.10.110:8888地址发送json报⽂,返回的结果也是json报⽂。
主要代码如下:
1 String resp= null;
2 JSONObject obj = new JSONObject();
3 obj.put("name", "张三");
4 obj.put("age", "18");
5 String query = String();
6 log.info("发送到URL的报⽂为:");
7 log.info(query);
8 try {
9 URL url = new URL("10.10.10.110:8888"); //url地址
10
11 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
12 connection.setDoInput(true);
13 connection.setDoOutput(true);
14 connection.setRequestMethod("POST");
15 connection.setUseCaches(false);
16 connection.setInstanceFollowRedirects(true);
17 connection.setRequestProperty("Content-Type","application/json");
18 t();
19
20 try (OutputStream os = OutputStream()) {
21 os.Bytes("UTF-8"));
22 }
23
24 try (BufferedReader reader = new BufferedReader(
25 new InputStream()))) {
26 String lines;
27 StringBuffer sbf = new StringBuffer();
28 while ((lines = adLine()) != null) {
29 lines = new Bytes(), "utf-8");
30 sbf.append(lines);
31 }
32 log.info("返回来的报⽂:"+String());
33 resp = String();
34
35 }
36 connection.disconnect();
37
38 } catch (Exception e) {
39 e.printStackTrace();
40 }finally{
41 JSONObject json = (JSONObject)JSON.parse(resp);
42 }
⽹上还有⼀种拼json发送报⽂的⽅式,也把代码分享出来:
1 String resp = null;
2 String name = Parameter("userName");
3 String age = Parameter("userAge");
4 String query = "{\"name\":\""+name+"\",\"age\":\""+age+"\"}";
5
6 try {
7 URL url = new URL("10.10.10.110:8888"); //url地址
8
9 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
10 connection.setDoInput(true);
11 connection.setDoOutput(true);
12 connection.setRequestMethod("POST");
13 connection.setUseCaches(false);
14 connection.setInstanceFollowRedirects(true);
15 connection.setRequestProperty("Content-Type","application/json");
16 t();
17
18 try (OutputStream os = OutputStream()) {
19 os.Bytes("UTF-8"));
20 }
21
22 try (BufferedReader reader = new BufferedReader(
23 new InputStream()))) {
24 String lines;
25 StringBuffer sbf = new StringBuffer();
26 while ((lines = adLine()) != null) {
27 lines = new Bytes(), "utf-8");
28 sbf.append(lines);
29 }
30 log.info("返回来的报⽂:"+String());
31 resp = String();
32
33 }
34 connection.disconnect();
35
36 } catch (Exception e) {
37 e.printStackTrace();
38 }finally{
39 JSONObject json = (JSONObject)JSON.parse(resp);
40 }
两种⽅式其实都是⼀样的。写得不对的地⽅,往各位撸过的⼤拿指正~
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论