天天看點

使用HttpClient發送post和get請求三方接口

最近在用到了HttpClient發送post和get請求三方接口的需求,是以寫了個封裝類友善以後用到:

需要用到的一些jar的maven坐标:

<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.5</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.7</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.11</version>
        </dependency>

       <dependency>
         <groupId>commons-logging</groupId>
         <artifactId>commons-logging</artifactId>
         <version>1.2</version>
      </dependency>
           

HttpUtil封裝類:

package com.springboot.demo.test.service;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
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.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
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.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpCoreContext;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;

import java.io.*;
import java.util.*;

public class HttpUtil {
    private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
    private static RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();
    private static String chaset = "UTF-8";    // 預設編碼

    /**
     * 發送 GET 請求(HTTP),無參數
     * @param url
     * @return
     */
    public static String doGet(String url) {
        if (StringUtils.isBlank(url)) {
            return "url不能為空";
        }
        // 建立http GET請求
        logger.info("url:{}", url);
        HttpGet httpGet = new HttpGet(url);
        // 設定請求和傳輸逾時時間
        httpGet.setConfig(requestConfig);
        String result = "";
        try (CloseableHttpClient httpclient = HttpClients.createDefault();// 建立Httpclient對象
             CloseableHttpResponse response = httpclient.execute(httpGet);// 執行請求
        ) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                result = EntityUtils.toString(response.getEntity(), chaset);
                logger.info("HttpGet方式請求成功!傳回結果:{}", result);
            } else {
                logger.info("HttpGet方式請求失敗!狀态碼:" + statusCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 發送 GET 請求(HTTP),有參數
     * @param url
     * @param params
     * @return
     */
    public static String doGet(String url, Map<String, Object> params) {
        if (!CollectionUtils.isEmpty(params)) {
            StringBuffer extraUrl = new StringBuffer();
            int temp = 0;
            for (String key : params.keySet()) {
                if (temp == 0) {
                    extraUrl.append("?");
                } else {
                    extraUrl.append("&");
                }
                extraUrl.append(key).append("=").append(params.get(key));
                temp++;
            }
            url += extraUrl;
        }
        return doGet(url);
    }


	/**
     * 發送 GET 請求(HTTP),擷取跳轉的最終url連結傳回
     *
     * @param url
     * @return
     */
    public static String doGetJumpLink(String url) {
        if (StringUtils.isBlank(url)) {
            return "url不能為空";
        }
        // 建立http GET請求
        HttpGet httpGet = new HttpGet(url);
        HttpContext context = new BasicHttpContext();
        String currentUrl ="";
        try (CloseableHttpClient httpclient = HttpClients.createDefault();// 建立Httpclient對象
             CloseableHttpResponse response = httpclient.execute(httpGet,context);// 執行請求
        ) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
             return  currentUrl="HttpGet方式請求失敗!狀态碼:" + statusCode;

            }
            //logger.info("HttpGet方式請求成功!傳回結果:{}", result);
            HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(
                    HttpCoreContext.HTTP_REQUEST);
            HttpHost currentHost = (HttpHost)  context.getAttribute(
                    HttpCoreContext.HTTP_TARGET_HOST);
            currentUrl = (currentReq.getURI().isAbsolute()) ? currentReq.getURI().toString() : (currentHost.toURI() + currentReq.getURI());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return currentUrl;
    }
    

    /**
     * 發送 POST 請求(HTTP),無參數
     * @param url
     * @return
     */
    public static String doPost(String url) {
        return doPost(url, null);
    }

    /**
     * 發送 POST 請求(HTTP),有參數
     * @param url
     * @return
     */
    public static String doPost(String url, Map<String, Object> params) {
        // 建立http POST請求
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        httpPost.setHeader("Content-Type", "application/json");
        if (params != null) {
            httpPost.setEntity(new StringEntity(JSON.toJSONString(params), ContentType.create("application/json", "utf-8")));
        }
        String result = "";
        try (CloseableHttpClient httpclient = HttpClients.createDefault();// 建立Httpclient對象
             CloseableHttpResponse response = httpclient.execute(httpPost);// 執行請求
        ) {
            logger.info("httpPost:{}", httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                result = EntityUtils.toString(response.getEntity(), chaset);
                logger.info("HttpPost方式請求成功!傳回結果:{}", result);
            } else {
                logger.info("HttpPost方式請求失敗!狀态碼:" + statusCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }


public static String doPost1(String url, Map<String, Object> paramMap) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        String result = "";
        // 建立httpClient執行個體
        httpClient = HttpClients.createDefault();
        // 建立httpPost遠端連接配接執行個體
        HttpPost httpPost = new HttpPost(url);
        // 配置請求參數執行個體
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)// 設定連接配接主機服務逾時時間
                .setConnectionRequestTimeout(5000)// 設定連接配接請求逾時時間
                .setSocketTimeout(5000)// 設定讀取資料連接配接逾時時間
                .build();
        // 為httpPost執行個體設定配置
        httpPost.setConfig(requestConfig);
        // 設定請求頭
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
        // 封裝post請求參數
        if (null != paramMap && paramMap.size() > 0) {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            // 通過map內建entrySet方法擷取entity
            Set<Map.Entry<String, Object>> entrySet = paramMap.entrySet();
            // 循環周遊,擷取疊代器
            Iterator<Map.Entry<String, Object>> iterator = entrySet.iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> mapEntry = iterator.next();
                nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
            }
            // 為httpPost設定封裝好的請求參數
            try {
                httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        try {
            // httpClient對象執行post請求,并傳回響應參數對象
            httpResponse = httpClient.execute(httpPost);
            // 從響應對象中擷取響應内容
            HttpEntity entity = httpResponse.getEntity();
            result = EntityUtils.toString(entity);
        } catch (ClientProtocolException e) {
            logger.error("錯誤資訊: ", e);
        } catch (IOException e) {
            logger.error("錯誤資訊: ", e);
        } finally {
            // 關閉資源
            if (null != httpResponse) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }


	/**
     * 發送 POST 請求(HTTP),有參數和cookie
     *
     * @param url
     * @param  params 參數
     * @param cookie 例如:LBSESSION=NGEzODUyNjUtYjZkYy00ZmNkLWJhZTAtMDBmYWNjYzQzZjBi
     * @return
     */
    public static String doPost(String url, Map<String, Object> params, String cookie) {
        // 建立http POST請求
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        httpPost.setHeader("Content-Type", "application/json");
        if (params != null) {
            httpPost.setEntity(new StringEntity(JSON.toJSONString(params), ContentType.create("application/json", "utf-8")));
        }
        if (cookie != null) {
            httpPost.addHeader("Cookie", cookie);
        }
        String result = "";
        try (CloseableHttpClient httpclient = HttpClients.createDefault();// 建立Httpclient對象
             CloseableHttpResponse response = httpclient.execute(httpPost);// 執行請求
        ) {
            logger.info("httpPost:{}", httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                result = EntityUtils.toString(response.getEntity(), chaset);
                logger.info("HttpPost方式請求成功!傳回結果:{}", result);
            } else {
                logger.info("HttpPost方式請求失敗!狀态碼:" + statusCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }


 /**
     * 通過url下載下傳視訊
     *
     * @param url
     * @return
     */
    public static String downVideo(String url) {
        //預設下載下傳到D:\video\
        return downVideo(url, "D:\\video\\");
    }


    /**
     * 通過url下載下傳視訊
     *
     * @param url
     * @param filepath 下載下傳到本地的路徑
     * @return
     */
    public static String downVideo(String url, String filepath) {
        String filename="";
        try {
            //擷取視訊流
            HttpClient client = HttpClients.createDefault();
            HttpGet httpget = new HttpGet(url);
            HttpResponse response = client.execute(httpget);
            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();

            //filepath不是斜杠結束的在末尾添加斜杠
            if (filepath.length()-1!=filepath.lastIndexOf("\\")){
                filepath+="\\";
            }

            //如果沒有檔案夾,則建立
            File file = new File(filepath);
            if (!file.exists() && !file.isDirectory()) {
                file.mkdirs();
            }

            //擷取檔案夾下的檔案數量,檔案數量加一作為要下載下傳的檔案名
            int fileCount = 0;
            File[] list = file.listFiles();
            for (int i = 0; i < list.length; i++) {
                if (list[i].isFile()) {
                    fileCount++;
                }
            }
            fileCount += 1;

            //如果檔案不存在則建立檔案
            filename = filepath + fileCount + ".mp4";
            File file_name = new File(filename);
            if (!file_name.exists()) {
                //建立檔案
                file_name.createNewFile();
            }

            //視訊流寫入檔案
            FileOutputStream fileout = new FileOutputStream(file_name);
            BufferedInputStream buf = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int ch = 0;
            while ((ch = buf.read(buffer)) != -1) {
                fileout.write(buffer, 0, ch);
            }
            is.close();
            fileout.flush();
            fileout.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "下載下傳成功,檔案名:"+filename;
    }
}
           

用的時候直接調用就行,如:

Map<String, Object> map = new HashMap<>();
map.put("a", additionModel.getA());
map.put("b", additionModel.getB());
String result = HttpUtil.doGet("http://125.113.27.170:8080/query/v1/addition",map);
           

參考:

HttpClient 4 - how to capture last redirect URL

使用httpclient獲得伺服器跳轉之後的url!