CloseableHttpClient POST請求與GET請求

HttpClient和CloseableHttpClient的區別 

Interface HttpClient
Class CloseableHttpClient
一個是接口,一個是實現該接口的類

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * @Description Http遠程調用
 * @Author WangKun
 * @Date 2019/10/31 14:19
 * @Version
 */
public class HttpClientUtil {

    private static final Logger looger = LoggerFactory.getLogger(HttpClientUtil.class);

    /**
     * @param url
     * @param params
     * @throws
     * @Description GET請求
     * @Return java.lang.Object
     * @Date 2019-10-31 15:38:01
     * @Author WangKun
     **/
    public static Object sendGetByMap(String url, Map<String, String> params) throws Exception {
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {
            client = HttpClients.createDefault();
            URIBuilder uriBuilder = new URIBuilder(url);
            //設置參數
            if (null != params && params.size() > 0) {
                for (Entry<String, String> entry : params.entrySet()) {
                    uriBuilder.addParameter(entry.getKey(), entry.getValue());
                }
            }
            HttpGet httpGet = new HttpGet(uriBuilder.build());
//            httpGet.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));
            httpGet.setHeader(new BasicHeader("Content-Type", "application/json;charset=UTF-8"));
            // 執行get
            response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, "UTF-8");
            if (StringUtils.isNotBlank(result)) {
                return JSONArray.parseArray(result);
            }
        } catch (Exception e) {
            looger.error("HttpClientUtil GET請求失敗!", e);
        } finally {
            //釋放資源,必須關閉,否則線程池不回收
            response.close();
            client.close();
        }
        return null;
    }


    /**
     * @param url
     * @param params
     * @throws
     * @Description POST請求
     * @Return java.lang.Object
     * @Date 2019-10-31 15:41:57
     * @Author WangKun
     **/
    public static Object sendPostByMap(String url, Map<String, String> params) throws Exception {
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {
            client = HttpClients.createDefault();
            HttpPost post = new HttpPost(url);
            List<NameValuePair> nameValuePairList = new ArrayList<>();
            // 設置參數
            if (null != params && params.size() > 0) {
                for (Entry<String, String> entry : params.entrySet()) {
                    nameValuePairList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                StringEntity entity = new UrlEncodedFormEntity(nameValuePairList, "UTF-8");
                post.setEntity(entity);
            }
            post.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));
            post.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));

            // 執行post
            response = client.execute(post);
            String result = EntityUtils.toString(response.getEntity(), "UTF-8");
            if (StringUtils.isNotBlank(result)) {
                return JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            looger.error("HttpClientUtil POST請求失敗!", e);
        } finally {
            //釋放資源,必須關閉,否則線程池不回收
            response.close();
            client.close();
        }
        return null;
    }


    /**
     * @param url
     * @param json
     * @throws
     * @Description POST請求
     * @Return java.lang.Object
     * @Date 2019-10-31 16:26:14
     * @Author WangKun
     **/
    public static String sendPostByJson(String url, String json) throws Exception {
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {
            client = HttpClients.createDefault();
            HttpPost post = new HttpPost(url);
            StringEntity requestEntity = new StringEntity(json, "UTF-8");
            requestEntity.setContentEncoding("UTF-8");
            post.setHeader("Content-Type", "application/json;charset=UTF-8");
            post.setEntity(requestEntity);
            // 執行post
            response = client.execute(post);
            String result = EntityUtils.toString(response.getEntity(), "UTF-8");
            if (StringUtils.isNotBlank(result)) {
                return result;
            }
        } catch (Exception e) {
            looger.error("HttpClientUtil POST請求失敗!", e);
        } finally {
            //釋放資源,必須關閉,否則線程池不回收
            response.close();
            client.close();
        }
        return null;
    }

    /**
     * @param url
     * @throws
     * @Description 發送POST 請求沒有參數
     * @Return java.lang.Object
     * @Date 2019-11-06 10:59:34
     * @Author WangKun
     **/
    public static String sendGet(String url) throws Exception {
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {
            client = HttpClients.createDefault();
            URIBuilder uriBuilder = new URIBuilder(url);
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            httpGet.setHeader(new BasicHeader("Content-Type", "application/json;charset=UTF-8"));
            // 執行get
            response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, "UTF-8");
            if (StringUtils.isNotBlank(result)) {
                return result;
            }
        } catch (Exception e) {
            looger.error("HttpClientUtil GET請求失敗!", e);
        } finally {
            //釋放資源,必須關閉,否則線程池不回收
            response.close();
            client.close();
        }
        return null;
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章