HttpUtils

import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
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.methods.HttpRequestBase;
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.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * http请求封装类
 *
 * @author ldq
 */
public class HttpUtils {

    /**
     * 发送get请求
     *
     * @param url     地址
     * @param params  参数map
     * @param cookies cookie map
     * @return json格式结果
     */
    public static String get(String url, Map<String, Object> params, Map<String, String> cookies) throws IOException {
        CloseableHttpClient client = HttpClients.createDefault();

        // 封装参数
        if (params != null && params.size() > 0) {
            List<BasicNameValuePair> list = new ArrayList<>();
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                list.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
            String param = EntityUtils.toString(new UrlEncodedFormEntity(list, Consts.UTF_8));
            url = url + "?" + param;
        }
        HttpGet httpGet = new HttpGet(url);

        // 设置cookie
        setCookie(httpGet, cookies);

        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = client.execute(httpGet);
            HttpEntity entity = httpResponse.getEntity();
            return EntityUtils.toString(entity);
        } finally {
            closeResource(client, httpResponse);
        }
    }

    /**
     * 发送post请求
     *
     * @param url     地址
     * @param params  参数map
     * @param cookies cookie map
     * @return json格式结果
     */
    public static String post(String url, Map<String, Object> params, Map<String, String> cookies) throws IOException {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        // 封装参数
        if (params != null && params.size() > 0) {
            List<BasicNameValuePair> list = new ArrayList<>();
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                list.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list);
            httpPost.setEntity(formEntity);
        }

        // 设置cookie
        setCookie(httpPost, cookies);

        CloseableHttpResponse response = null;
        try {
            response = client.execute(httpPost);
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity);
        } finally {
            closeResource(client, response);
        }
    }

    /**
     * 发送post json请求
     *
     * @param url     地址
     * @param params  参数json
     * @param cookies cookie map
     * @return json格式结果
     */
    public static String post(String url, String params, Map<String, String> cookies) throws IOException {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json");
        // 封装参数
        if (StringUtils.isNotBlank(params)) {
            // 防止中文乱码
            httpPost.setEntity(new StringEntity(params, "UTF-8"));
        }

        // 设置cookie
        setCookie(httpPost, cookies);

        CloseableHttpResponse response = null;
        try {
            response = client.execute(httpPost);
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity);
        } finally {
            closeResource(client, response);
        }
    }

    /**
     * 发送post json请求
     *
     * @param url    地址
     * @param params 参数json
     * @param header header
     * @return json格式结果
     */
    public static String postRequest(String url, String params, Map<String, String> header) throws IOException {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json");

        if (header != null) {
            for (Map.Entry<String, String> entry : header.entrySet()) {
                httpPost.addHeader(entry.getKey(), entry.getValue());
            }
        }
        // 封装参数
        if (StringUtils.isNotBlank(params)) {
            // 防止中文乱码
            httpPost.setEntity(new StringEntity(params, "UTF-8"));
        }

        CloseableHttpResponse response = null;
        try {
            response = client.execute(httpPost);
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity);
        } finally {
            closeResource(client, response);
        }
    }

    /**
     * 设置cookie
     */
    private static void setCookie(HttpRequestBase httpRequestBase, Map<String, String> cookies) {
        // 设置cookie
        if (cookies != null && cookies.size() > 0) {
            StringBuilder cookie = new StringBuilder();
            for (Map.Entry<String, String> entry : cookies.entrySet()) {
                cookie.append(entry.getKey()).append("=").append(entry.getValue()).append(";");
            }
            httpRequestBase.addHeader("Cookie", cookie.toString());
        }
    }

    /**
     * 关闭流
     */
    private static void closeResource(CloseableHttpClient client, CloseableHttpResponse response) throws IOException {
        if (response != null) {
            response.close();
        }
        if (client != null) {
            client.close();
        }
    }

}

 

posted @ 2022-10-28 21:01  MING5135  阅读(20)  评论(0编辑  收藏  举报