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.運行截圖

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM