HttpClient 工具类

来自姬鸿昌的知识库
跳到导航 跳到搜索

https://www.bilibili.com/video/BV1AN411Z7mx?p=12

pom.xml

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

HttpClientUtil.java

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.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.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpClientUtil {

    public static String doGet(String url, Map<String, String> param) {
        // 创建Httpclient 对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;

        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建 HTTP GET 请求
            HttpGet httpGet = new HttpGet(uri);

            //执行请求
            response = httpclient.execute(httpGet);

            //判断返回状态是否为 200
            if (response.getStatusLine().getStatusCode() == 200) {

                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");

            }

        } catch (Exception e) {
            e.printStackTrace();

        } finally {

            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return resultString;
        }
    }


    public static String doGet(String url) {
        return doGet(url, null);
    }

    public static String doPost(String url, Map<String, String> param) {
        // 创建 Httpclient 对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建 Http Post 请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }

                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "UTF-8");
                httpPost.setEntity(entity);
            }

            // 执行 HTTP 请求
            response = httpClient.execute(httpPost);

            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        return resultString;

    }


    public static String doPost(String url) {
        return doPost(url, null);
    }

    public static String doPostJson(String url, String json) {
        // 创建 Httpclient 对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";

        //执行 http 请求
        try {
            //创建 Http Post 请求
            HttpPost httpPost = new HttpPost(url);

            //创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();

        } finally {

            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;

    }

}

JsonUtils.java

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;
import java.util.Map;

public class JsonUtils {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 将对象转换成 JSON 字符串
     * @param data
     * @return
     */
    public static String objectToJson(Object data) {
        String string = null;
        try {
            string = MAPPER.writeValueAsString(data);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return string;
    }

    /**
     * 将 json 结果集转化为对象
     * @param jsonData json 数据
     * @param beanType 对象中的 object 类型
     * @return
     * @param <T>
     */
    public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
        T t = null;
        try {
            t = MAPPER.readValue(jsonData, beanType);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return t;
    }

    /**
     * 将 json 数据转换成 pojo 对象 list
     * @param jsonData
     * @param beanType
     * @return
     * @param <T>
     */
    public static <T> List<T> jsonToList(String jsonData, Class<T> beanType) {
        JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
        List<T> list = null;
        try {
            list = MAPPER.readValue(jsonData, javaType);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 把 json 转换为 Map 工具方法
     * @param jsonData
     * @param keyType
     * @param valueType
     * @return
     * @param <K>
     * @param <V>
     */
    public static <K, V> Map<K, V> jsonToMap(String jsonData, Class<K> keyType, Class<V> valueType) {
        JavaType javaType = MAPPER.getTypeFactory().constructMapType(Map.class, keyType, valueType);
        Map<K, V> map = null;
        try {
             map = MAPPER.readValue(jsonData, javaType);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return map;
    }

}

ClientApplicationTests.java

import io.github.jihch.pojo.People;
import io.github.jihch.utils.HttpClientUtil;
import org.junit.jupiter.api.Test;
import org.junit.runners.Parameterized;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SpringBootTest
public class ClientApplicationTests {

    @Test
    void httpClientGet() {
        String result = HttpClientUtil.doGet("http://localhost:8080/demo");
        System.out.println(result);

        result = HttpClientUtil.doGet("http://localhost:8080/demo5");
        System.out.println(result);
        ObjectMapper objectMapper = new ObjectMapper();
        People people = null;
        try {
            people = objectMapper.readValue(result, People.class);
            System.out.println(people);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        result = HttpClientUtil.doGet("http://localhost:8080/demo2?name=jihch&age=15");
        System.out.println(result);

        result = HttpClientUtil.doGet("http://localhost:8080/demo6");
        System.out.println(result);
        List<People> list = JsonUtils.jsonToList(result, People.class);
        System.out.println(list);
        for (People p : list) {
            System.out.println(p);
        }

        Map<String, String> map = new HashMap<>();
        map.put("name", "jihch");
        map.put("age", "15");
        result = HttpClientUtil.doGet("http://localhost:8080/demo2", map);
        System.out.println(result);
    }

}
demo
{"id":1,"name":"jihch"}
People{id=1, name='jihch'}
name:jihch,age:15
[{"id":1,"name":"jihch1"},{"id":2,"name":"jihch2"}]
[People{id=1, name='jihch1'}, People{id=2, name='jihch2'}]
People{id=1, name='jihch1'}
People{id=2, name='jihch2'}
name:jihch,age:15