前言
现在对接接口数据,都有一些很好用的工具类,例如:RestTemplate,但有些场景还是需要我们自己手动去实现,而且自己实现一遍也有利我们理解。废话不多说了,现在通过HttpURLConnection来发起get、post请求。
Get请求
@GetMapping("/getMethod")
public String testGetMethod() {
String result = "";
String path = "http://127.0.0.1:8083/device/list?pageNo=1&pageSize=5&deviceType=IPC";
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置请求方式
conn.setRequestMethod(HttpMethod.GET.name());
// 设置超时时间
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
int code = conn.getResponseCode();
// 2xxx成功 3xxx重定向 4xxx资源错误 5xxx服务器错误
if (code == 200) {
InputStream is = conn.getInputStream();
// 从输入流读取字符串,指定编码格式为UTF-8,不然会出现乱码的问题。
result = StreamUtils.copyToString(is, Charset.forName("UTF-8"));
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
StreamUtils是Spring框架的一个数据流工具类,这边大家也可以自己实现,下面贴一下源码
/**
* Copy the contents of the given InputStream into a String.
* Leaves the stream open when done.
* @param in the InputStream to copy from (may be {@code null} or empty)
* @return the String that has been copied to (possibly empty)
* @throws IOException in case of I/O errors
*/
public static String copyToString(@Nullable InputStream in, Charset charset) throws IOException {
if (in == null) {
return "";
}
StringBuilder out = new StringBuilder();
InputStreamReader reader = new InputStreamReader(in, charset);
char[] buffer = new char[BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = reader.read(buffer)) != -1) {
out.append(buffer, 0, bytesRead);
}
return out.toString();
}
Post请求
post请求传参的时候一般有两种方式:RequestParam和RequestBody。
RequestParam
使用类似于get方式的key-value传参方式,Content-Type为application/x-www-form-urlencoded。

@GetMapping("/postMethod")
public String testPostMethod() {
String result = "";
String path = "http://127.0.0.1:8083/device/query";
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置请求方式
conn.setRequestMethod(HttpMethod.POST.name());
// 设置传参方式,当服务端通过@RequestParam接受参数时,使用application/x-www-form-urlencoded
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
// 设置超时时间
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
String param = "pageNo=1&pageSize=5&deviceType=IPC";
conn.setDoOutput(true);
conn.getOutputStream().write(param.getBytes(Charset.forName("UTF-8")));
int code = conn.getResponseCode();
if (code == 200) {
InputStream is = conn.getInputStream();
// 从输入流读取字符串,指定编码格式为UTF-8,不然会出现乱码的问题。
result = StreamUtils.copyToString(is, Charset.forName("UTF-8"));
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
RequestBody
一般使用json格式传递参数,Content-Type为application/json。

@GetMapping("/postJsonMethod")
public String testPostJsonMethod() {
String result = "";
String path = "http://127.0.0.1:8083/device/create";
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置请求方式
conn.setRequestMethod(HttpMethod.POST.name());
// 设置传参方式,当服务端通过@RequestBody接受参数时,使用application/json
conn.setRequestProperty("Content-Type","application/json");
// 设置超时时间
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
JSONObject param = new JSONObject();
param.put("id", "0019318cac98402e83f3367102360777");
param.put("deviceType", "IPC");
param.put("name", "测试");
param.put("gbid", "31011700041325005777");
param.put("status", 1);
param.put("latitude", 0.0);
param.put("longitude", 0.0);
conn.setDoOutput(true);
conn.getOutputStream().write(param.toJSONString().getBytes(Charset.forName("UTF-8")));
int code = conn.getResponseCode();
if (code == 200) {
InputStream is = conn.getInputStream();
// 从输入流读取字符串,指定编码格式为UTF-8,不然会出现乱码的问题。
result = StreamUtils.copyToString(is, Charset.forName("UTF-8"));
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
注:读取数据的时候一定要指定编码格式为UTF-8,不然会出现乱码的问题。
本文详细介绍了如何使用HttpURLConnection发起GET和POST请求,包括RequestParam和RequestBody两种传参方式,并提供了完整的代码示例。
311

被折叠的 条评论
为什么被折叠?



