1. 程式人生 > >封裝http請求

封裝http請求

在開發當中調其他系統請求或模擬前端調請求有時會使用到http請求,但java原生類還是比較難用的,一般會自己封裝一下,本文展示http請求的一般封裝,可以直接拷貝使用。

package com.zqsign.app.privatearbitrate.util;

import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpClientUtil {

    public static String doGet(String url, Map<String, String> param) {


        // 建立Httpclient物件
        CloseableHttpClient httpclient = createCustomClient();

        String resultString = null;
        CloseableHttpResponse response = null;
        try {
            // 建立uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            // 建立http GET請求
            HttpGet httpGet = new HttpGet(uri);
            // 執行請求
            response = httpclient.execute(httpGet);
            // 判斷返回狀態是否為200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String doGet(String url) {
        return doGet(url, null);
    }

    public static String doPost(String url, Map<String, String> param) {
        // 建立Httpclient物件
        CloseableHttpClient httpClient = createCustomClient();
        CloseableHttpResponse response = null;
        String resultString = null;
        try {
            // 建立Http Post請求
            HttpPost httpPost = new HttpPost(url);
            // 建立引數列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<NameValuePair>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模擬表單
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
                httpPost.setEntity(entity);
            }
            // 執行http請求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

    public static String doPost(String url, String body) {
        // 建立Httpclient物件
        CloseableHttpClient httpClient = createCustomClient();
        CloseableHttpResponse response = null;
        String resultString = null;
        try {
            // 建立Http Post請求
            HttpPost httpPost = new HttpPost(url);
            if (body != null) {
                httpPost.setEntity(new StringEntity(body, "utf-8"));
            }
            // 執行http請求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

    public static String doPost(String url) {
        return doPost(url, (String) null);
    }

    public static String doPostJson(String url, String json, Header... headers) {
        // 建立Httpclient物件
        CloseableHttpClient httpClient = createCustomClient();
        CloseableHttpResponse response = null;
        String resultString = null;
        try {
            // 建立Http Post請求
            HttpPost httpPost = new HttpPost(url);
            //新增請求頭
            if (headers != null && headers.length > 0) {
                for (Header header : headers) {
                    if (header != null) {
                        httpPost.addHeader(header);
                    }
                }
            }
            // 建立請求內容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 執行http請求
            response = httpClient.execute(httpPost);
            if(response.getStatusLine().getStatusCode() == 200) {
            	resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            }else {
            	resultString = "呼叫服務端異常,請聯絡相關人員";
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static CloseableHttpClient createCustomClient() {
        RequestConfig defaultRequestConfig = RequestConfig.custom()
                .setSocketTimeout(120 * 1000)
                .setConnectTimeout(120 * 1000)
                .setConnectionRequestTimeout(120 * 1000)
                .setStaleConnectionCheckEnabled(true)
                .build();

        return HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
    }
}

使用:

  @Test
    public void evidenceTest() {

        long a = System.currentTimeMillis();
        Map<String,Object> param = getParam("evidence");
        long b = System.currentTimeMillis();
        System.out.println("拼接資料時間:" + (b-a));
        String str = JSON.toJSONString(param);
        String sign = RsaSign.sign(str, TENANT_PRIVATE_KEY);
        BasicHeader header = new BasicHeader("sign_val", sign);
        System.out.println(str);

        long start = System.currentTimeMillis();
        String res = HttpClientUtil.doPostJson("http://localhost:8080/web/trade-upload", JSON.toJSONString(param),header);
        long end = System.currentTimeMillis();

        System.out.println("請求介面時間:" + (end-start));
        System.out.println("介面反饋資訊:" + res);

    }

當然,現在已經不用自己封裝了,spring3.0之後提供了org.springframework.web.client.RestTemplate類來供我們傳送http請求。