Java 发送 Http 请求工具类(HttpClient)

import com.gientech.exception.BusinessException;
import com.gientech.util.LoggerUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
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.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;

/**
 *
 * HttpClient
 * @author xiarg
 * @date 2023/11/1 17:18
 */
public class TdspHttpClient {

    private static final Logger logger = LoggerFactory.getLogger(TdspHttpClient.class);

    @Autowired
    private static CloseableHttpClient httpClient;

    static {
        httpClient = HttpClientBuilder.create().build();
    }

    /**
     *
     * http的get请求
     * @param url 请求路径
     * @return null
     * @author xiarg
     * @date 2023/11/2 13:35
     */
    public static String sendGetRequest(String url,String responseCharset) throws Exception{
        LoggerUtil.info(logger, "[HttpClientUtils.sendGetRequest]=====>>>>>接口请求start<<<<<===== {0}", url);
        HttpEntity entity = null;
        String result = null;
        try {
            HttpGet httpGet = new HttpGet(url);
            HttpResponse response = httpClient.execute(httpGet);
            return handleResponse( response, responseCharset);
        } catch (IOException e) {
            LoggerUtil.info(logger, "[HttpClientUtils.sendGetRequest]=====>>>>>发送请求出现异常<<<<<===== {0}",
                    e.getMessage());
            e.printStackTrace();
        } catch (ParseException e) {
            LoggerUtil.info(logger, "[HttpClientUtils.sendGetRequest]=====>>>>>发送请求出现异常<<<<<===== {0}",
                    e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                EntityUtils.consume(entity);
            } catch (IOException e) {
                LoggerUtil.info(logger, "[HttpClientUtils.sendGetRequest]=====>>>>>清理缓存出现异常<<<<<===== {0}",
                        e.getMessage());
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     *
     * http的post秦秋
     * @param url
     * @param requestBody
     * @param contentType 媒体类型
     * @param entryCharset 请求报文编码
     * @param responseCharset 响应报文编码
     * @return null
     * @author xiarg
     * @date 2023/11/2 13:36
     */
    public static String sendPostRequest(String url, String requestBody, String contentType ,String entryCharset,
                                         String responseCharset) throws Exception{
        LoggerUtil.info(logger, "[HttpClientUtils.sendPostRequest]=====>>>>>接口请求start<<<<<===== {0}", url);
        HttpEntity entity = null;
        String result = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            ContentType entryContentType = ContentType.create(contentType, Charset.forName(entryCharset));
            httpPost.setEntity(new StringEntity(requestBody, entryContentType));
            HttpResponse response = httpClient.execute(httpPost);
            return handleResponse(response,responseCharset);
        } catch (UnsupportedCharsetException e) {
            LoggerUtil.info(logger, "[HttpClientUtils.sendGetRequest]=====>>>>>发送请求出现异常<<<<<===== {0}",
                    e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            LoggerUtil.info(logger, "[HttpClientUtils.sendGetRequest]=====>>>>>发送请求出现异常<<<<<===== {0}",
                    e.getMessage());
            e.printStackTrace();
        } catch (ParseException e) {
            LoggerUtil.info(logger, "[HttpClientUtils.sendGetRequest]=====>>>>>发送请求出现异常<<<<<===== {0}",
                    e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                EntityUtils.consume(entity);
            } catch (IOException e) {
                LoggerUtil.info(logger, "[HttpClientUtils.sendGetRequest]=====>>>>>清理缓存出现异常<<<<<===== {0}",
                        e.getMessage());
                e.printStackTrace();
            }
        }
        return result;
    }

    private static String handleResponse(HttpResponse response,String responseCharset) throws IOException,BusinessException{
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode >= 200 && statusCode < 300) {
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity,Charset.forName(responseCharset));
            LoggerUtil.info(logger, "[HttpClientUtils.sendGetRequest]=====>>>>>接口请求返回结果<<<<<===== {0}",
                    result);
            return result;
        }
        throw new BusinessException("调用接口出现异常!");
    }


}

        此工具类可以直接复制使用。

  • 10
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中有多种HTTP请求工具类可供使用,其中一种是http-request。它基于URLConnection实现,不依赖于HttpClient。使用http-request发送GET请求示例如下: 1. 引入依赖: ``` <dependency> <groupId>com.github.kevinsawicki</groupId> <artifactId>http-request</artifactId> <version>5.6</version> </dependency> ``` 2. 发送GET请求获取响应报文: ```java String response = HttpRequest.get("http://www.baidu.com").body(); System.out.println("Response was: " + response); ``` 3. 发送GET请求获取响应码: ```java int code = HttpRequest.get("http://google.com").code(); ``` 除了http-request,还有其他一些常用的HTTP请求工具类,比如HttpUtil。使用HttpUtil发送GET请求的示例代码如下: ```java // 最简单的HTTP请求,自动判断编码 String result1 = HttpUtil.get("https://www.baidu.com"); // 自定义请求页面的编码 String result2 = HttpUtil.get("https://www.baidu.com", CharsetUtil.CHARSET_UTF_8); // 传入http参数,参数会自动做URL编码,拼接在URL中 HashMap<String, Object> paramMap = new HashMap<>(); paramMap.put("city", "北京"); String result3 = HttpUtil.get("https://www.baidu.com", paramMap); ``` 如果需要发送POST请求,可以使用HttpUtil的post方法,示例代码如下: ```java HashMap<String, Object> paramMap = new HashMap<>(); paramMap.put("city", "北京"); String result = HttpUtil.post("https://www.baidu.com", paramMap); ``` 另外,如果需要文件上传,可以将参数中的键指定为"file",值设为文件对象即可,示例代码如下: ```java HashMap<String, Object> paramMap = new HashMap<>();paramMap.put("file", FileUtil.file("D:\\face.jpg")); String result = HttpUtil.post("https://www.baidu.com", paramMap); ``` 以上是一些常用的Java HTTP请求工具类,你可以根据具体需求选择适合的工具类发送HTTP请求。请问您还有其他相关问题吗? 相关问题: 1. Java中还有哪些常用的HTTP请求工具类? 2. 如何处理HTTP请求的返回结果? 3. 如何设置HTTP请求的超时时间?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值