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

使用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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是一个通用的Java HTTP请求工具类,可以用于发送HTTPS请求: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; public class HttpUtils { /** * 发送HTTP GET请求 * @param url 请求的URL地址 * @return 响应结果 */ public static String sendHttpGet(String url) throws Exception { URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); int responseCode = con.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // 成功 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); return response.toString(); } else { throw new Exception("HTTP请求失败,返回码:" + responseCode); } } /** * 发送HTTPS GET请求 * @param url 请求的URL地址 * @return 响应结果 */ public static String sendHttpsGet(String url) throws Exception { SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, new TrustManager[] {new X509TrustManager() { public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) {} public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) {} public java.security.cert.X509Certificate[] getAcceptedIssuers() {return new java.security.cert.X509Certificate[0];} }}, new java.security.SecureRandom()); URL obj = new URL(url); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); con.setSSLSocketFactory(sslcontext.getSocketFactory()); con.setRequestMethod("GET"); int responseCode = con.getResponseCode(); if (responseCode == HttpsURLConnection.HTTP_OK) { // 成功 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); return response.toString(); } else { throw new Exception("HTTPS请求失败,返回码:" + responseCode); } } } ``` 这个工具类使用了Java标准库中的`HttpURLConnection`和`HttpsURLConnection`来发送HTTP/HTTPS请求,并且支持GET请求方式。在发送HTTPS请求时,需要先自定义一个`TrustManager`,并且将其设为SSLContext的默认信任管理器,这样才能避免SSL证书验证失败的问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@是小白吖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值