天天看點

java使用httpclient發送http請求

HttpClient 是 Apache Jakarta Common 下的子項目,用來提供高效的、最新的、功能豐富的支援 HTTP 協定的用戶端程式設計工具包,将httpclient封裝成一個工具類,友善直接調用

環境:jdk1.8+maven

1.引入maven依賴

<!-- 引入httpclient依賴-->
		<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5</version>
        </dependency>
        <!--将資料實體為json-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.62</version>
        </dependency>
           

2.編寫工具類

public class HttpRequestUtils {

    private static void httpRespond(HttpUriRequest httpRequest,HttpRespCallBack httpRespCallBack) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpResponse response = null;
        try {
            // 由用戶端執行(發送)Get請求
            response = httpClient.execute(httpRequest);
            // 從響應模型中擷取響應實體
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                httpRespCallBack.resp(response);
            }else {
                throw new RuntimeException("響應内容為空");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }  finally {
            try {
                // 釋放資源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 發送get請求
     * @param url 請求位址
     * @param httpRespCallBack 響應内容
     */
    public static void sendHttGet(String url,HttpRespCallBack httpRespCallBack){
        HttpGet get=new HttpGet(url);
        httpRespond(get,httpRespCallBack);
    }

    /**
     *發送post請求
     * @param url 請求位址
     * @param params 請求參數
     * @param httpRespCallBack 請求回調
     */
    public static void sendHttpPost(String url, Map<String,Object> params,HttpRespCallBack httpRespCallBack){
        HttpPost post=new HttpPost(url);
        HttpEntity httpEntity=new StringEntity(JSONObject.toJSONString(params),"utf-8");
        post.setEntity(httpEntity);
        post.setHeader("Content-Type", "application/json;charset=utf8");
        httpRespond(post,httpRespCallBack);
    }

    /**
     * put請求
     * @param url 請求位址
     * @param params 請求參數
     * @param httpRespCallBack 請求回調
     */
    public static void sendHttpPut(String url,Map<String,Object> params,HttpRespCallBack httpRespCallBack){
        HttpPut httpPut=new HttpPut(url);
        HttpEntity httpEntity=new StringEntity(JSONObject.toJSONString(params),"utf-8");
        httpPut.setEntity(httpEntity);
        httpPut.setHeader("Content-Type", "application/json;charset=utf8");
        httpRespond(httpPut,httpRespCallBack);
    }

    /**
     * delete請求
     * @param url 請求位址
     * @param httpRespCallBack 請求回調
     */
    public static void sendHttpDelete(String url,HttpRespCallBack httpRespCallBack){
        HttpDelete httpDelete=new HttpDelete(url);
        httpRespond(httpDelete,httpRespCallBack);
    }
           

3.請求響應接口

@FunctionalInterface
public interface HttpRespCallBack {
    void resp(HttpResponse httpResponse) ;
}
           

4.請求測試

/**
     * get請求
     */
    public static void doGetTest() {

        HttpRequestUtils.sendHttGet("http://localhost:8081/pcp/basic/dict/findAll",(response)->{
            try {
                System.out.println(EntityUtils.toString(response.getEntity()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }


    /**
     * post請求
     *
     * @date 2018年7月13日 下午4:18:50
     */
    public static void doPostTest() {
        Map<String,Object> map=new HashMap<>();
        map.put("locationCode","ABCDEFGH");
        HttpRequestUtils.sendHttpPost("http://localhost:8081/pcp/basic/location/add",map,
                (resp)->{
                    try {
                        System.out.println(EntityUtils.toString(resp.getEntity()));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
    }

    //delete請求
    public static void doDeleteTest() {
        HttpRequestUtils.sendHttpDelete("http://localhost:8081/pcp/basic/location/delete?id=1", (response) -> {
            try {
                System.out.println(EntityUtils.toString(response.getEntity()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }