1. 程式人生 > 其它 >記錄自己寫的HttpClientUtils基於HttpClient

記錄自己寫的HttpClientUtils基於HttpClient

上程式碼

package com.test.common.util;

import com.hangyjx.business.create_template.StringUtil;
import com.lowagie.text.pdf.codec.Base64;
import org.apache.axis.types.Entity;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpClientUtil {
    
    
    /**
     * 傳送get請求
     * @param url
     * @param headers
     * @return
     */
    public static String doGet (String url, Map<String,String> headers){
        HttpGet get = new HttpGet();
        HttpResponse response  = null;
        try {
            get.setURI(new URI(url));
            if (MapUtils.isNotEmpty(headers)) {
                for (Map.Entry<String,String> entry: headers.entrySet()) {
                    get.addHeader(entry.getKey(),entry.getValue());
                }
            }else {
                //沒有傳headers的預設情況
                get.addHeader("Content-Type", "application/json");
            }
            HttpClient httpClient = HttpClients.createDefault();
            response = httpClient.execute(get);
            System.out.println("傳輸資料:url"+url+":"+get);
            return EntityUtils.toString(response.getEntity(),"UTF-8");
        }catch (Exception e){
            System.out.println("請求異常:"+url);
            throw new RuntimeException("請求異常:" + url, e);
        }finally {
            if(response!=null){
                EntityUtils.consumeQuietly(response.getEntity());
            }
            get.releaseConnection();
        }
    }



    /**
     * 傳送post請求
     * @param url
     * @param postData
     * @param headers
     * @return
     */
    public static String dopost(String url, String postData , Map<String,String> headers){
        HttpPost post = new HttpPost();
        HttpResponse response  = null;
        try {
            post.setURI(new URI(url));
            if(StringUtils.isNotBlank(postData)){
                post.setEntity(new StringEntity(postData,"UTF-8"));
            }
            if (MapUtils.isNotEmpty(headers)) {
                for (Map.Entry<String,String> entry: headers.entrySet()) {
                    post.addHeader(entry.getKey(),entry.getValue());
                }
            }else {
                //沒有傳headers的預設情況
                post.addHeader("Content-Type", "application/json");
            }
            HttpClient httpClient = HttpClients.createDefault();
            response = httpClient.execute(post);
            System.out.println("傳輸資料:url"+url+":"+postData);
            return EntityUtils.toString(response.getEntity(),"UTF-8");
        }catch (Exception e){
            System.out.println("請求異常:"+url);
            throw new RuntimeException("請求異常:" + url, e);
        }finally {
            if(response!=null){
                EntityUtils.consumeQuietly(response.getEntity());
            }
            post.releaseConnection();
        }
    }

    /**
     * 根據url下載檔案
     * @param url
     * @param filepath
     * @return
     */
    public static String download(String url,String filepath){
        try{
            HttpClient client = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse response =client.execute(httpGet);
            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();
            if (filepath==null){
                //獲取預設路徑
            }

            File file = new File(filepath);
            file.getParentFile().mkdirs();
            FileOutputStream fileout = new FileOutputStream(file);
            /**
             * 根據實際執行效果 設定緩衝區大小
             */
            byte[] buffer = new byte[1024];
            int ch = 0;
            while ((ch = is.read(buffer)) != -1) {
                fileout.write(buffer, 0, ch);
            }
            is.close();
            fileout.flush();
            fileout.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 以form表單形式提交資料,傳送post請求
     * @explain
     *   1.請求頭:httppost.setHeader("Content-Type","application/x-www-form-urlencoded")
     *   2.提交的資料格式:key1=value1&key2=value2...
     * @param url 請求地址
     * @param paramsMap 具體資料
     * @return 伺服器返回資料
     */
    public static String httpPostWithForm(String url,Map<String, String> paramsMap){
        // 用於接收返回的結果
        String resultData ="";
        try {
            HttpPost post = new HttpPost(url);
            List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
            // 迭代Map-->取出key,value放到BasicNameValuePair物件中-->新增到list中
            for (String key : paramsMap.keySet()) {
                pairList.add(new BasicNameValuePair(key, paramsMap.get(key)));
            }
            UrlEncodedFormEntity uefe = new UrlEncodedFormEntity(pairList, "utf-8");
            post.setEntity(uefe);
            // 建立一個http客戶端
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            // 傳送post請求
            HttpResponse response = httpClient.execute(post);

            // 狀態碼為:200
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                // 返回資料:
                resultData = EntityUtils.toString(response.getEntity(),"UTF-8");
            }else{
                throw new RuntimeException("介面連線失敗!");
            }
        } catch (Exception e) {
            throw new RuntimeException("介面連線失敗!");
        }
        return resultData;
    }
}