HttpCli简单使用及工具类分享

1.环境

- JDK1.8
- httpclient 4.5.2

2.Maven依赖

	<dependencies>
        <!--httpclient依赖-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>
        <!--JSON转换工具-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.4</version>
        </dependency>
        <!--单元测试依赖-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!--以JDK1.8编译-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

3.HttpCli工具类

package cn.memoing.httpcli;


import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

/***
 *
 * @author: chenjiacheng
 * @date: 2018-11-26 11:46
 * @Description: HttpCliUtils 自定义工具类
 */
public class HttpCliUtils {

    private static final CloseableHttpClient client = HttpClients.createDefault();

    /**
     * Post请求
     *
     * @param url
     * @param json
     * @param headers
     * @return
     */
    public static void doPost(String url, JSONObject json, Header... headers) {
        //1.创建post请求
        HttpPost httpPost = new HttpPost(url);
        //2.设置请求头
        if (headers != null && headers.length > 0) {
            httpPost.setHeaders(headers);
        }
        //3.设置请求参数
        StringEntity entity = null;
        try {
            entity = new StringEntity(json.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        //4.设置编码及内容类型
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);

        //5.执行请求,打印输出
        executeHttpRequest(httpPost);
    }

    /**
     * put请求
     *
     * @param url
     * @param json
     * @param headers
     */
    public static void doPut(String url, JSONObject json, Header... headers) {
        //1.创建put请求
        HttpPut httpPut = new HttpPut(url);
        //2.设置请求头
        if (httpPut != null && headers.length > 0) {
            httpPut.setHeaders(headers);
        }
        //3.设置请求参数
        StringEntity entity = null;
        try {
            entity = new StringEntity(json.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        //4.设置编码及内容类型
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPut.setEntity(entity);
        //5.执行请求,打印输出
        executeHttpRequest(httpPut);
    }

    /**
     * Get请求
     *
     * @param url
     * @param paramsMap
     * @param headers
     */
    public static void doGet(String url, Map<String, Object> paramsMap, Header... headers) {
        //1. 拼接Url参数
        String parpms = "";
        if (paramsMap != null && !(paramsMap.isEmpty())) {
            String paramMapFormat = paramsMap.entrySet().stream()
                    .filter(a->!"".equals(a.getValue()))
                    .map(a -> {
                String temp = "";
                if (a.getValue() instanceof int[]) {
                    if (((int[]) a.getValue()).length > 1) {
                        int[] values = (int[]) a.getValue();
                        for (int i = 0; i < values.length - 1; i++) {
                            temp += a.getKey() + "=" + values[i] + "&";
                        }
                        temp += a.getKey() + "=" + values[values.length - 1];
                    }
                } else {
                    if (!"".equals(a.getValue())) {
                        temp = a.getKey() + "="+a.getValue();
                    }
                }
                return temp;
            }).collect(Collectors.joining("&"));
            String param = Arrays.stream(paramMapFormat.split("&+")).collect(Collectors.joining("&"));
            System.out.println("paramMapFormat = " + paramMapFormat);
            if (!("".equals(param))) {
                if(param.substring(0,1).equals("&")){
                    param = param.substring(1);
                }
                parpms = "?" + param;
            }

        }

        String absUrl = url + parpms;
        System.out.println("absUrl = " + absUrl);

        //2.创建httpGet
        HttpGet httpGet = new HttpGet(absUrl);
        //3.设置请求头
        if (headers != null && headers.length > 0) {
            httpGet.setHeaders(headers);
        }
        //4.执行请求,打印输出
        executeHttpRequest(httpGet);
    }


    /**
     * delete请求
     *
     * @param url
     * @param paramsMap
     * @param headers
     */
    public static void doDelete(String url, Map<String, Object> paramsMap, Object[] objParms, Header... headers) {
        //1. 拼接Url参数
        String parpms = "";

        if (paramsMap != null && !(paramsMap.isEmpty())) {
            parpms = paramsMap.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue()).collect(Collectors.joining("&"));
            parpms = "?" + parpms;
        } else if (objParms != null && objParms.length > 0) {
            parpms = "/";
            for (int i = 0; i < objParms.length - 1; i++) {
                parpms += objParms[i] + "/";
            }
            parpms += objParms[objParms.length - 1];
        }
        String absUrl = url + parpms;
        System.out.println("absUrl = " + absUrl);
        //2.创建httpGet
        HttpDelete httpDelete = new HttpDelete(url + parpms);
        //3.设置请求头
        if (headers != null && headers.length > 0) {
            httpDelete.setHeaders(headers);
        }
        //4.执行请求,打印输出
        executeHttpRequest(httpDelete);
    }

    /**
     * 执行请求
     *
     * @param httpRequestBase
     * @return
     */
    private static void executeHttpRequest(HttpRequestBase httpRequestBase) {
        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = client.execute(httpRequestBase);
            HttpEntity httpEntity = httpResponse.getEntity();
            formatPrint(EntityUtils.toString(httpEntity));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 格式化打印
     *
     * @param jsonObj
     */
    private static void formatPrint(String jsonObj) {
        int level = 0;
        StringBuffer jsonForMatStr = new StringBuffer();
        for (int index = 0; index < jsonObj.length(); index++) {
            char c = jsonObj.charAt(index);
            if (level > 0 && '\n' == jsonForMatStr.charAt(jsonForMatStr.length() - 1)) {
                jsonForMatStr.append(getLevelStr(level));
            }
            switch (c) {
                case '{':
                case '[':
                    jsonForMatStr.append(c + "\n");
                    level++;
                    break;
                case ',':
                    jsonForMatStr.append(c + "\n");
                    break;
                case '}':
                case ']':
                    jsonForMatStr.append("\n");
                    level--;
                    jsonForMatStr.append(getLevelStr(level));
                    jsonForMatStr.append(c);
                    break;
                default:
                    jsonForMatStr.append(c);
                    break;
            }
        }
        System.out.println(jsonForMatStr);
    }

    /**
     * 格式化参数处理
     *
     * @param level
     * @return
     */
    private static String getLevelStr(int level) {
        StringBuffer levelStr = new StringBuffer();
        for (int levelI = 0; levelI < level; levelI++) {
            levelStr.append("  ");
        }
        return levelStr.toString();
    }


}

猜你喜欢

转载自blog.csdn.net/Agan__/article/details/84564463