Java后端调用Api接口



1.Get方式调用接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@GetMapping("/httpGet")
public String httpGet() throws Exception {
String str = "";
JSONObject result = null;
String urls = "http://localhost:8088/userInfo/";
URL url = new URL(urls);
//打开和url之间的连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
PrintWriter out = null;
//请求方式
conn.setRequestMethod("GET");
//设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.connect();
try(InputStream is = conn.getInputStream();) {
// 构造一个字符流缓存
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while ((str = br.readLine()) != null) {
result = JSONObject.parseObject(str);
}
logger.info("获取到的报文数据为:{}", result);
} finally {
// 关闭连接
conn.disconnect();
}
return "SUCCESS-httpGet";
}

2.Post方式调用接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
@GetMapping("/httpPost")
public String httpPost() throws Exception{
URL url = new URL("http://localhost:8088/userInfo/");
//打开和url之间的连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
PrintWriter out = null;
//请求方式 这里设置你需要请求的方式
conn.setRequestMethod("POST");
//设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
// 这里设置请求头
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
//设置是否向httpUrlConnection输出,设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
//最常用的Http请求无非是get和post,get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,
//post与get的 不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
conn.setDoOutput(true);
conn.setDoInput(true);
//获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
//发送请求参数即数据
JSONObject param = new JSONObject();
param.put("key", "我要带参发送数据");
out.write(param.toJSONString());
//缓冲数据
out.flush();
//获取URLConnection对象对应的输入流
try (InputStream is = conn.getInputStream()){
//构造一个字符流缓存
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String str = "";
while ((str = br.readLine()) != null) {
param = JSONObject.parseObject(str);
}
logger.info("获取到的报文数据为:{}", param);
} finally {
//断开连接,最好写上,disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
//固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些。
conn.disconnect();
}
return "HTTP-POST";
}

3.完整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
package cn.blue.easypoi.controller;

import cn.blue.easypoi.bean.UserInfo;
import cn.blue.easypoi.service.UserInfoService;
import com.alibaba.fastjson.JSONObject;
import org.omg.CORBA.NameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import sun.net.www.http.HttpClient;
import sun.net.www.protocol.http.HttpURLConnection;

import javax.annotation.Resource;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
* @author Blue
* @date 2020/4/28
**/
@RestController
@RequestMapping("/userInfo")
public class UserController {
@Resource
private UserInfoService userInfoService;

private Logger logger = LoggerFactory.getLogger(UserController.class);

@GetMapping("/")
public Map<String, Object> test1() {
UserInfo userInfo = new UserInfo();
userInfo.setName(UUID.randomUUID().toString());
userInfo.setSex(0);
userInfoService.insertOne(userInfo);
Map<String, Object> map = new HashMap<>();
map.put("code", 200);
map.put("result", userInfo);
map.put("success", "true");
return map;
}

/**
*
* @return
*/
@PostMapping("/")
public Map<String, Object> test2(@RequestBody JSONObject jsonObject) {
UserInfo userInfo = new UserInfo();
userInfo.setName(UUID.randomUUID().toString());
userInfo.setSex(0);
userInfoService.insertOne(userInfo);
JSONObject map = new JSONObject();
map.put("code", 200);
map.put("result", userInfo);
map.put("success", "true");
return map;
}

@GetMapping("/httpPost")
public String httpPost() throws Exception{
JSONObject param = new JSONObject();
param.put("key", "value");

URL url = new URL("http://localhost:8088/userInfo/");
//打开和url之间的连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
PrintWriter out = null;
//请求方式 这里设置你需要请求的方式
conn.setRequestMethod("POST");
//设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
// 这里设置请求头
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
//设置是否向httpUrlConnection输出,设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
//最常用的Http请求无非是get和post,get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,
//post与get的 不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
conn.setDoOutput(true);
conn.setDoInput(true);
//获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
//发送请求参数即数据
out.write(param.toJSONString());
//缓冲数据
out.flush();
//获取URLConnection对象对应的输入流
try (InputStream is = conn.getInputStream()){
//构造一个字符流缓存
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String str = "";
while ((str = br.readLine()) != null) {
param = JSONObject.parseObject(str);
}
logger.info("获取到的报文数据为:{}", param);
} finally {
//断开连接,最好写上,disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
//固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些。
conn.disconnect();
}
return "HTTP-POST";
}

@GetMapping("/httpGet")
public String httpGet() throws Exception {
String str = "";
JSONObject result = null;
String urls = "http://localhost:8088/userInfo/";
URL url = new URL(urls);
//打开和url之间的连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
PrintWriter out = null;
//请求方式
conn.setRequestMethod("GET");
//设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.connect();
try(InputStream is = conn.getInputStream();) {
// 构造一个字符流缓存
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while ((str = br.readLine()) != null) {
result = JSONObject.parseObject(str);
}
logger.info("获取到的报文数据为:{}", result);
} finally {
// 关闭连接
conn.disconnect();
}
return "SUCCESS-httpGet";
}

}

参考文档

打赏
  • 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!
  1. © 2020-2021 coderblue    湘ICP备20003709号

请我喝杯咖啡吧~

支付宝
微信