使用HttpURLConnection发送GET,POST请求

接口项目地址:https://github.com/Nguyen-Vm/s-program

API:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@RestController
@RequestMapping("/area")
public class AreaController {
@Autowired
private AreaService areaService;

@RequestMapping(value = "/list", method = RequestMethod.GET)
private Map<String, Object> listArea(){
Map<String, Object> modelMap = new HashMap<>();
List<Area> areaList = areaService.getAreaList();
modelMap.put("list", areaList);
return modelMap;
}

@RequestMapping(value = "/insert", method = RequestMethod.POST)
private Map<String, Object> insertArea(@RequestBody Area area){
Map<String, Object> modelMap = new HashMap<>();
boolean result = areaService.addArea(area);
modelMap.put("result", result);
return modelMap;
}

}

发送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
public class Main {

public static void main(String[] args) throws IOException {

InetAddress inetAddress = InetAddress.getLocalHost();
// 获取本地IP
String hostName = inetAddress.getHostAddress();

String getUrlStr = String.format("http://%s:%s/s-program/area/list", hostName, 8080);
get(getUrlStr);
}

public static void get(String urlStr) throws IOException {
URL url = new URL(urlStr);

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

// 返回结果-字节输入流转换成字符输入流,控制台输出字符
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
System.out.println(sb);
}
}

发送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
public class Main {

public static void main(String[] args) throws IOException {

InetAddress inetAddress = InetAddress.getLocalHost();
// 获取本地IP
String hostName = inetAddress.getHostAddress();

String postUrlStr = String.format("http://%s:%s/s-program/area/insert", hostName, 8080);
post(postUrlStr, "{\"areaName\": \"中国上海\", \"priority\": 1}");


}

public static void post(String urlStr, String body) throws IOException {
URL url = new URL(urlStr);

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
// 设置Content-Type
connection.setRequestProperty("Content-Type", "application/json");
// 设置是否向httpUrlConnection输出,post请求设置为true,默认是false
connection.setDoOutput(true);

// 设置RequestBody
PrintWriter printWriter = new PrintWriter(connection.getOutputStream());
printWriter.write(body);
printWriter.flush();

// 返回结果-字节输入流转换成字符输入流,控制台输出字符
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
System.out.println(sb);
}
}