概述

Java可以实现HTTP请求的方法有很多,下面我列举了一些:

  1. RestTemplate,这个是Spring提供的,可以减少引入的依赖
  2. HTTPClient
  3. Hutool工具类库,这个使用最方便且有详细的中文文档
  4. OkHttp

要测试的接口

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
package com.ledao.springbootdemo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* @author LeDao
* @company
* @create 2023-01-12 5:30
*/
@RestController
@RequestMapping("/hello")
public class HelloController {

@GetMapping("/doGet")
public String doGet(String city) {
return "Hello " + city;
}

@PostMapping("/doPost")
public String doPost(String str) {
return str;
}
}

RestTemplate

介绍

RestTemplate是Spring用于同步client端的核心类,简化了与http服务的通信,并满足RestFul原则,程序代码可以给它提供URL,并提取结果

代码实现

get请求

参数既可以直接拼接在url中,也可以使用Map设置并传入(使用Map感觉更麻烦)

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
package com.ledao.springbootdemo;

import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
* @author LeDao
* @company
* @create 2023-01-12 5:45
*/
public class Test {

public static void main(String[] args) {
//创建RestTemplate对象
RestTemplate restTemplate = new RestTemplate();
//请求的url,这里需要拼接参数,不然无法传参成功
String url = "http://localhost:8080/hello/doGet?city={city}";
//设置参数
Map<String, String> params = new HashMap<>(16);
params.put("city", "北京");
//得到请求的结果
String result = restTemplate.getForObject(url, String.class, params);
//打印结果
System.out.println(result);
}
}

自动拼接Map中的参数,url中只需要写接口

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
package com.ledao.springbootdemo;

import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
* @author LeDao
* @company
* @create 2023-01-12 5:45
*/
public class Test {

public static void main(String[] args) {
//创建RestTemplate对象
RestTemplate restTemplate = new RestTemplate();
//设置参数
Map<String, Object> params = new HashMap<>(16);
params.put("city", "北京");
//请求的url
StringBuilder url = new StringBuilder("http://localhost:8080/hello/doGet");
//用于记录当前是第几个参数
int index = 0;
//开始拼接参数
for (String key : params.keySet()) {
//第一个参数前要加上一个问号
if (index == 0) {
url.append("?").append(key).append("=").append(params.get(key)).append("&");
} else {
url.append(key).append("=").append(params.get(key)).append("&");
}
index++;
}
//得到请求的结果
String result = restTemplate.getForObject(url.toString(), String.class);
//打印结果
System.out.println(result);
}
}

封装拼接参数的代码

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
package com.ledao.springbootdemo.util;

import java.util.Map;

/**
* @author LeDao
* @company
* @create 2023-01-16 19:27
*/
public class MyUtil {

/**
* 获得自动拼接参数后的url
*
* @param url
* @param params
* @return
*/
public static String getUrl(String url, Map<String, Object> params) {
//请求的url
StringBuilder resultUrl = new StringBuilder(url);
//用于记录当前是第几个参数
int index = 0;
//开始拼接参数
for (String key : params.keySet()) {
//第一个参数前要加上一个问号
if (index == 0) {
resultUrl.append("?").append(key).append("=").append(params.get(key)).append("&");
} else {
resultUrl.append(key).append("=").append(params.get(key)).append("&");
}
index++;
}
return resultUrl.toString();
}
}

使用封装的方法

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
package com.ledao.springbootdemo;

import com.ledao.springbootdemo.util.MyUtil;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
* @author LeDao
* @company
* @create 2023-01-12 5:45
*/
public class Test {

public static void main(String[] args) {
//创建RestTemplate对象
RestTemplate restTemplate = new RestTemplate();
//设置参数
Map<String, Object> params = new HashMap<>(16);
params.put("city", "北京");
//得到请求的结果
String result = restTemplate.getForObject(MyUtil.getUrl("http://localhost:8080/hello/doGet", params), String.class);
//打印结果
System.out.println(result);
}
}

post请求

这里有个坑,不能使用HashMap传参,要使用LinkedMultiValueMap

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
package com.ledao.springbootdemo;

import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
* @author LeDao
* @company
* @create 2023-01-12 5:45
*/
public class Test {

public static void main(String[] args) {
//创建RestTemplate对象
RestTemplate restTemplate = new RestTemplate();
//请求的url
String url = "http://localhost:8080/hello/doPost";
//设置参数
LinkedMultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
params.add("str", "12345678910");
//得到请求的结果
String result = restTemplate.postForObject(url, params, String.class);
//打印结果
System.out.println(result);
}
}

HTTPClient

引入依赖

1
2
3
4
5
6
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.14</version>
</dependency>

代码实现

工具类

getpost请求封装成工具类以便调用

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
package com.ledao.springbootdemo.util;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Map;

/**
* HttpClient工具类
*
* @author LeDao
* @company
* @create 2023-01-12 6:13
*/
public class HttpClientUtil {

/**
* 发送get请求
*
* @param url 请求的url
* @param params 参数
* @return
* @throws Exception
*/
public static String sendGet(String url, List<NameValuePair> params) throws Exception {
//创建一个HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建一个url对象
URIBuilder builder = new URIBuilder(url);
//设置参数
builder.addParameters(params);
//创建GET请求
HttpGet get = new HttpGet(builder.build());
//执行请求
CloseableHttpResponse response = httpClient.execute(get);
//状态码
int code = response.getStatusLine().getStatusCode();
System.out.println(code);
//得到的结果
String content = EntityUtils.toString(response.getEntity(), "utf-8");
//关闭连接
response.close();
httpClient.close();
//返回结果
return content;
}

/**
* 发送post请求
*
* @param url 请求的url
* @param params 参数
* @return
* @throws Exception
*/
public static String sendPost(String url, List<NameValuePair> params) throws Exception {
//创建一个HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建一个url对象
URIBuilder builder = new URIBuilder(url);
//设置参数
builder.addParameters(params);
//创建GET请求
HttpPost post = new HttpPost(builder.build());
//执行请求
CloseableHttpResponse response = httpClient.execute(post);
//状态码
int code = response.getStatusLine().getStatusCode();
System.out.println(code);
//得到的结果
String content = EntityUtils.toString(response.getEntity(), "utf-8");
//关闭连接
response.close();
httpClient.close();
//返回结果
return content;
}
}

测试

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
package com.ledao.springbootdemo;

import com.ledao.springbootdemo.util.HttpClientUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.List;

/**
* @author LeDao
* @company
* @create 2023-01-12 5:45
*/
public class Test {

public static void main(String[] args) throws Exception {
//请求的url
String url = "http://localhost:8080/hello/doGet";
//设置参数
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("city", "北京"));
//得到请求的结果
String content = HttpClientUtil.sendGet(url, params);
//打印结果
System.out.println(content);
}
}
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
package com.ledao.springbootdemo;

import com.ledao.springbootdemo.util.HttpClientUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.List;

/**
* @author LeDao
* @company
* @create 2023-01-12 5:45
*/
public class Test {

public static void main(String[] args) throws Exception {
//请求的url
String url = "http://localhost:8080/hello/doPost";
//设置参数
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("str", "123456"));
//得到请求的结果
String content = HttpClientUtil.sendPost(url, params);
//打印结果
System.out.println(content);
}
}

Hutool工具类库

引入依赖

下面这个依赖是Hutool工具类库完整依赖,如果还使用到Hutool的其它工具类就使用完整依赖

1
2
3
4
5
6
<!-- https://mvnrepository.com/artifact/cn.hutool/hutool-all -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.11</version>
</dependency>

下面这个依赖是Hutool工具类库HTTP请求的依赖,如果只使用到Hutool工具类库的HTTP请求,就选择下面这个

1
2
3
4
5
6
<!-- https://mvnrepository.com/artifact/cn.hutool/hutool-http -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-http</artifactId>
<version>5.8.11</version>
</dependency>

代码实现

如果要实现更复杂的请求可以去使用Http请求-HttpRequest,下面代码只是传了参数然后发起请求

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
package com.ledao.springbootdemo;

import cn.hutool.http.HttpUtil;

import java.util.HashMap;

/**
* @author LeDao
* @company
* @create 2023-01-12 5:45
*/
public class Test {

public static void main(String[] args) {
//要请求的url
String url = "http://localhost:8080/hello/doGet";
//设置参数
HashMap<String, Object> paramMap = new HashMap<>(16);
paramMap.put("city", "北京");
//发起请求
String str = HttpUtil.get(url, paramMap);
//打印结果
System.out.println(str);
}
}

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
package com.ledao.springbootdemo;

import cn.hutool.http.HttpUtil;

import java.util.HashMap;

/**
* @author LeDao
* @company
* @create 2023-01-12 5:45
*/
public class Test {

public static void main(String[] args) {
//要请求的url
String url = "http://localhost:8080/hello/doPost";
//设置参数
HashMap<String, Object> paramMap = new HashMap<>(16);
paramMap.put("str", "北京");
//发起请求
String str = HttpUtil.post(url, paramMap);
//打印结果
System.out.println(str);
}
}

OkHttp

引入依赖

1
2
3
4
5
6
<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.10.0</version>
</dependency>

代码实现

工具类

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
package com.ledao.springbootdemo.util;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

/**
* OkHttp工具类
*
* @author LeDao
* @company
* @create 2023-01-12 7:00
*/
public class OkHttpUtil {

/**
* 发送get请求
*
* @param url 请求的url
* @return
* @throws IOException
*/
public static String sendGet(String url) throws IOException {
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.get()
.build();
try (Response response = okHttpClient.newCall(request).execute()) {
return response.body().string();
}
}

/**
* 发送post请求
*
* @param url 请求的url
* @param formBody 携带参数
* @return
* @throws IOException
*/
public static String sendPost(String url, FormBody formBody) throws IOException {
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
try (Response response = okHttpClient.newCall(request).execute()) {
return response.body().string();
}
}
}

测试

get请求

参数拼接在url中,需要自己手动拼接,也可以使用上面RestTemplate中封装的代码来自动拼接参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.ledao.springbootdemo;

import com.ledao.springbootdemo.util.OkHttpUtil;

/**
* @author LeDao
* @company
* @create 2023-01-12 5:45
*/
public class Test {

public static void main(String[] args) throws Exception {
//请求的url
String url = "http://localhost:8080/hello/doGet?city=北京";
//得到请求的结果
String result = OkHttpUtil.sendGet(url);
//打印结果
System.out.println(result);
}
}
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
package com.ledao.springbootdemo;

import com.ledao.springbootdemo.util.OkHttpUtil;
import okhttp3.FormBody;

/**
* @author LeDao
* @company
* @create 2023-01-12 5:45
*/
public class Test {

public static void main(String[] args) throws Exception {
//请求的url
String url = "http://localhost:8080/hello/doPost";
//设置参数,有几个参数就有几个add()
FormBody formBody = new FormBody.Builder()
.add("str", "12345678910")
.build();
//得到请求的结果
String result = OkHttpUtil.sendPost(url, formBody);
//打印结果
System.out.println(result);
}
}