【Java工具类】Java HttpUtils工具类-Apache CloseableHttpClient、Spring RestTemplate

657 阅读1分钟

原文链接:HttpUtils工具类

使用Apache CloseableHttpClient实现

Maven依赖

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

POST请求

import org.apache.http.HttpEntity;
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.util.EntityUtils;

import java.io.Closeable;
import java.io.IOException;
import java.net.URI;
import java.util.Map;
import java.util.Set;

public class HttpUtils {
    public static String doPost(String url, Map<String, String> headers, String jsonParam) {
        System.out.println(" = = 请求地址 = = > > > > > > " + url);
        System.out.println(" = = 请求参数 = = > > > > > > " + jsonParam);
        // 创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = "";
        try {
            // 创建http请求
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/json");
            // 创建请求内容
            StringEntity entity = new StringEntity(jsonParam);
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            // 设置请求头
            if (null != headers && !headers.isEmpty()) {
                System.out.println(" = = 请求头 = = > > > > > > ");
                Set<Map.Entry<String, String>> entries = headers.entrySet();
                for (Map.Entry<String, String> e : entries) {
                    System.out.println(e.getKey() + ":" + e.getValue());
                    httpPost.setHeader(e.getKey(), e.getValue());
                }
            }
            response = httpClient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 释放资源
            closeResource(response, httpClient);
        }
        return result;
    }

    private static void closeResource(Closeable... resources) {
        System.out.println("> > > > > > > > > > 关闭流资源 > > > > > > > > > >");
        try {
            for (Closeable resource : resources) {
                if (resource != null) {
                    resource.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Get请求

public static String doGet(String url, Map<String, String> headMap, Map<String, String> paramMap) {
    System.out.println(" = = 请求地址 = = > > > > > > " + url);
    // 创建Httpclient对象
    CloseableHttpClient httpClient = HttpClients.createDefault();
    String result = "";
    CloseableHttpResponse response = null;
    try {
        // 创建uri
        URIBuilder builder = new URIBuilder(url);
        if (paramMap != null && !paramMap.isEmpty()) {
            Set<Map.Entry<String, String>> entrySet = paramMap.entrySet();
            for (Map.Entry<String, String> entry : entrySet) {
                builder.addParameter(entry.getKey(), entry.getValue());
            }
        }
        URI uri = builder.build();

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

        //添加请求头
        if (headMap != null && !headMap.isEmpty()) {
            Set<Map.Entry<String, String>> entries = headMap.entrySet();
            System.out.println(" = = 请求头 = = > > > > > > ");
            for (Map.Entry<String, String> e : entries) {
                System.out.println(e.getKey() + ":" + e.getValue());
                httpGet.addHeader(e.getKey(), e.getValue());
            }
        }

        // 执行请求
        response = httpClient.execute(httpGet);
        // 判断返回状态是否为200
        HttpEntity entity = response.getEntity();
        result = EntityUtils.toString(entity, "utf-8");
        System.out.println(" = = 请求返回 = = > > > > > > " + result);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        closeResource(response, httpClient);
    }
    return result;
}

private static void closeResource(Closeable... resources) {
    System.out.println("> > > > > > > > > > 关闭流资源 > > > > > > > > > >");
    try {
        for (Closeable resource : resources) {
            if (resource != null) {
                resource.close();
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

使用Spring RestTemplate实现

Maven依赖

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>5.3.19</version>
</dependency>

发送POST请求

public static Object doPost(String url) {
    try {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        Map<Object, Object> map = new HashMap<>();
        map.put("","");
        HttpEntity<Map<Object, Object>> entity = new HttpEntity<>(map, headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        return response;
    } catch (RestClientException e) {
        e.printStackTrace();
        return null;
    }
}

发送Get请求

public static Object doGet(String url) {
    try {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        Map<Object, Object> map = new HashMap<>();
        HttpEntity<Map<Object, Object>> entity = new HttpEntity<>(map, headers);
        ResponseEntity<Object> response = restTemplate.exchange(url, HttpMethod.GET, entity, Object.class);
        return response;
    } catch (RestClientException e) {
        e.printStackTrace();
        return null;
    }
}