SpringBoot(四)——http请求工具类
记录一下单元测试中使用的http工具类,一般只需要留意路径、请求体、请求头。至少目前遇到的是这样。
GetMapping没有请求体,传参的话直接用用?和&连接写在请求路径里,例如"?id=10086&age=22"
PostMapping有请求体,以JSON格式传递的
1.路径
例如,[ http://localhost:8080 ],这是基本路径,一般在公共接口里定义。后续的RequestMapping和GetMapping等具体路径在测试方法里自行拼接。
2.请求头一般携带密钥,一般在公共接口里定义,其他测试类直接实现获取请求头。
import java.util.HashMap;
import java.util.Map;
public interface TestBase { //String IP = "10.8.45.120"; String IP = "localhost"; int PORT = 8103; String BAST_PATH = "http://" + IP + ":" + (PORT); //默认的密钥 String AUTHORIZATION = "Basic c2FiZXI6c2FV0"; String SCC_AUTH = "bearer eyJ0eXAiOiJKc29uV2ViVG9rZ"; default Map<String, String> getHead() { Map<String, String> head = new HashMap<>(); head.put("authorization", AUTHORIZATION); head.put("scc-auth", SCC_AUTH); return head; } }
3.封装get请求和post请求于一个工具类
import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.MapUtils; import org.apache.http.HttpEntity; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; import java.io.IOException; import java.util.Map; /** * http 请求工具类 */ @Slf4j public final class HttpRequestUtils { //设置字符编码 private static final String CHARSET = "UTF-8"; private static RequestConfig defaultRequestConfig = RequestConfig .custom() //设置等待数据超时时间 .setSocketTimeout(30000) //设置连接超时时间 .setConnectTimeout(30000) //设置从连接池获取连接的等待超时时间 .setConnectionRequestTimeout(30000) //.setStaleConnectionCheckEnabled(true) .build(); //释放资源,httpResponse为响应流,httpClient为请求客户端 private static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException { if (httpResponse != null) { httpResponse.close(); } if (httpClient != null) { httpClient.close(); } } //get请求带参数、带请求头 public static String get(String urlWithParams, Map<String, String> header) throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpget = new HttpGet(urlWithParams); if (!MapUtils.isEmpty(header)) { header.forEach(httpget::addHeader); } CloseableHttpResponse response = httpClient.execute(httpget); HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity, CHARSET); httpget.releaseConnection(); release(response, httpClient); return result; } public static String get(String urlWithParams) throws IOException { return get(urlWithParams, null); } //发送post请求,带json请求体和请求头 public static String postJson(String url, String json, Map<String, String> headersMap) { RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); for (Map.Entry<String, String> entry : headersMap.entrySet()) { headers.add(entry.getKey(),entry.getValue()); } org.springframework.http.HttpEntity<String> request = new org.springframework.http.HttpEntity<>(json, headers); ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class); return response.getBody(); } }
4.单元测试
import org.junit.jupiter.api.Test; import java.io.IOException; public class GoodsCategoryMapperTest implements TestBase{ private static final String PRE = BAST_PATH + "/goodsCategory"; @Test public void test1() throws IOException { String url = "/getGoodsCategory?category_id=29"; String s = HttpRequestUtils.get(PRE + url, getHead()); System.out.println(s); } @Test public void test2() throws IOException { String url = "/getGoodsCategoryListInfo?page_index=1&page_size=10"; String params = "{\n" + " \"brandId\":\"1000000005\"\n" + "}"; String s = HttpRequestUtils.postJson(PRE + url, params, getHead()); System.out.println(s); } }
5.运行截图