概述
Java可以实现HTTP请求的方法有很多,下面我列举了一些:
- RestTemplate,这个是Spring提供的,可以减少引入的依赖
- HTTPClient
- Hutool工具类库,这个使用最方便且有详细的中文文档
- 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;
@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;
public class Test {
public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); 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;
public class Test {
public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); Map<String, Object> params = new HashMap<>(16); params.put("city", "北京"); 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;
public class MyUtil {
public static String getUrl(String url, Map<String, Object> params) { 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;
public class Test {
public static void main(String[] args) { 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;
public class Test {
public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); 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
| <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.14</version> </dependency>
|
代码实现
工具类
把get
和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 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;
public class HttpClientUtil {
public static String sendGet(String url, List<NameValuePair> params) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); URIBuilder builder = new URIBuilder(url); builder.addParameters(params); 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; }
public static String sendPost(String url, List<NameValuePair> params) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); URIBuilder builder = new URIBuilder(url); builder.addParameters(params); 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;
public class Test {
public static void main(String[] args) throws Exception { 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;
public class Test {
public static void main(String[] args) throws Exception { 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的其它工具类就使用完整依赖
1 2 3 4 5 6
| <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
| <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;
public class Test {
public static void main(String[] args) { 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;
public class Test {
public static void main(String[] args) { 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
| <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;
public class OkHttpUtil {
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(); } }
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;
public class Test {
public static void main(String[] args) throws Exception { 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;
public class Test {
public static void main(String[] args) throws Exception { String url = "http://localhost:8080/hello/doPost"; FormBody formBody = new FormBody.Builder() .add("str", "12345678910") .build(); String result = OkHttpUtil.sendPost(url, formBody); System.out.println(result); } }
|