httpUtil

本文介绍了一种使用Maven进行HTTP请求处理的方法,包括httpclient依赖的配置,自定义的HTTP请求与响应模型,以及GET和POST请求的具体实现。通过示例代码展示了如何设置请求参数、请求头,以及如何处理响应。

需要在maven中导入的依赖:

        <!--http通讯依赖-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.8</version>
        </dependency>

 

自己组建的httpReqModel以及httpResqModel(后续功能强大了,我这边会继续添加的)

public class HttpReqModel {
    private String url;
    private Map<String,String> header;
    private Map<String,String> params;
    private int readTimeout;

    public int getReadTimeout() {
        return readTimeout;
    }

    public void setReadTimeout(int readTimeout) {
        this.readTimeout = readTimeout;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public Map<String, String> getHeader() {
        return header;
    }

    public void setHeader(Map<String, String> header) {
        this.header = header;
    }

    public Map<String, String> getParams() {
        return params;
    }

    public void setParams(Map<String, String> params) {
        this.params = params;
    }
}
public class HttpResqModel {
    private int statusCode;
    private String returnMsg;

    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public String getReturnMsg() {
        return returnMsg;
    }

    public void setReturnMsg(String returnMsg) {
        this.returnMsg = returnMsg;
    }
}

然后就是httpUtil了

import com.eszb.john.sbsm.common.exception.HttpStatusException;
import com.eszb.john.sbsm.common.exception.ParseMsgException;
import com.eszb.john.sbsm.common.exception.TelnetException;
import com.eszb.john.sbsm.common.net.model.HttpReqModel;
import com.eszb.john.sbsm.common.net.model.HttpResqModel;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.LinkedList;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

public class HttpUtil {
    /**
     * 连接池中的最大连接数
     */
    private static final int MAX_CONN_TOTAL = 10;
    /**
     * 连接同一个route最大的并发数
     */
    private static int MAX_CONN_PER_ROUTE = 10;
    /**
     * 从连接池中获取可用连接最大超时时间 单位:毫秒
     */
    private static int CONNECT_REQUEST_TIMEOUT = 1000;
    /**
     * 连接目标url最大超时 单位:毫秒
     */
    private static int CONNECT_TIMEOUT = 1000;
    /**
     * 等待响应(读数据)最大超时 单位:毫秒
     */
    private static int SOCKET_TIMEOUT = 1000;

    /**
     * httpGet方法
     *
     * @param reqModel
     * @return
     * @throws TelnetException
     * @throws URISyntaxException
     * @throws IOException
     * @throws HttpStatusException
     */
    public static HttpResqModel httpGet(HttpReqModel reqModel) throws TelnetException, URISyntaxException, IOException, HttpStatusException, ParseMsgException {
        String url = reqModel.getUrl();
        if (Objects.isNull(url)) {
            throw new TelnetException("request httpGet Method url为空");
        }
        URIBuilder uriBuilder = new URIBuilder(url);
        //设置请求参数
        Map<String, String> params = reqModel.getParams();
        if (!CollectionUtils.isEmpty(params)) {
            LinkedList<NameValuePair> list = new LinkedList<>();
            Set<String> keySet = params.keySet();
            for (String k : keySet) {
                list.add(new BasicNameValuePair(k, params.get(k)));
            }
            uriBuilder.setParameters(list);
        }

        HttpGet httpGet = new HttpGet(uriBuilder.build());
        //设置请求头
        Map<String, String> header = reqModel.getHeader();
        if (!CollectionUtils.isEmpty(header)) {
            Set<String> keySet = header.keySet();
            for (String k : keySet) {
                httpGet.addHeader(k, header.get(k));
            }
        }
        //设置读取时间
        int socketTimeout = SOCKET_TIMEOUT;
        if (0 != reqModel.getReadTimeout()) {
            socketTimeout = reqModel.getReadTimeout();
        }
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(CONNECT_REQUEST_TIMEOUT)
                .setConnectTimeout(CONNECT_TIMEOUT)
                .setSocketTimeout(socketTimeout)
                .build();

        HttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(MAX_CONN_TOTAL)
                .setMaxConnPerRoute(MAX_CONN_PER_ROUTE)
                .setDefaultRequestConfig(requestConfig)
                .build();

        HttpResponse httpResponse = null;
        try {
            //执行http请求
            httpResponse = httpClient.execute(httpGet);
        } catch (IOException e) {
            throw new IOException();
        }
        StatusLine statusLine = httpResponse.getStatusLine();
        HttpResqModel resqModel = new HttpResqModel();
        int statusCode = statusLine.getStatusCode();
        resqModel.setStatusCode(statusCode);

        //非200状态的处理
        if (HttpStatus.SC_OK != statusCode) {
            throw new HttpStatusException(statusCode, null);
        }
        HttpEntity httpEntity = httpResponse.getEntity();
        String entity = null;
        try {
            entity = EntityUtils.toString(httpEntity, "utf-8");
        } catch (IOException e) {
            throw new ParseMsgException(statusCode,"报文数据报文解析异常"+httpEntity.toString());
        }
        resqModel.setReturnMsg(entity);
        return resqModel;
    }

    /**
     * httpPost方法
     *
     * @param reqModel
     * @return
     */
    public static HttpResqModel httpPost(HttpReqModel reqModel) throws TelnetException, HttpStatusException, ParseMsgException, UnsupportedEncodingException {
        String url = reqModel.getUrl();
        if (Objects.isNull(url)) {
            throw new TelnetException("request httpGet Method url为空");
        }
        HttpPost httpPost = new HttpPost(url);
        //设置post请求头
        Map<String, String> header = reqModel.getHeader();
        if (!CollectionUtils.isEmpty(header)) {
            Set<String> keySet = header.keySet();
            for (String k : keySet) {
                httpPost.addHeader(k, header.get(k));
            }
        }
        //设置参数
        Map<String, String> params = reqModel.getParams();
        if (!CollectionUtils.isEmpty(header)) {
            LinkedList<NameValuePair> pairs = new LinkedList<>();
            Set<String> keySet = params.keySet();
            for (String k : keySet) {
                pairs.add(new BasicNameValuePair(k,params.get(k)));
            }
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,"utf-8");
            httpPost.setEntity(entity);
        }
        //设置读取时间
        int socketTimeout = SOCKET_TIMEOUT;
        if (0 != reqModel.getReadTimeout()) {
            socketTimeout = reqModel.getReadTimeout();
        }
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(CONNECT_REQUEST_TIMEOUT)
                .setConnectTimeout(CONNECT_TIMEOUT)
                .setSocketTimeout(socketTimeout)
                .build();

        HttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(MAX_CONN_TOTAL)
                .setMaxConnPerRoute(MAX_CONN_PER_ROUTE)
                .setDefaultRequestConfig(requestConfig)
                .build();

        HttpResponse response = null;
            //执行http请求
        try {
            response = httpClient.execute(httpPost);
        } catch (IOException e) {
            e.printStackTrace();
        }

        StatusLine statusLine = response.getStatusLine();
        HttpResqModel resqModel = new HttpResqModel();
        int statusCode = statusLine.getStatusCode();
        resqModel.setStatusCode(statusCode);

        //非200状态的处理
        if (HttpStatus.SC_OK != statusCode) {
            throw new HttpStatusException(statusCode, null);
        }
        HttpEntity httpEntity = response.getEntity();
        String entity = null;
        try {
            entity = EntityUtils.toString(httpEntity, "utf-8");
        } catch (IOException e) {
            throw new ParseMsgException(statusCode,"报文数据报文解析异常"+httpEntity.toString());
        }
        resqModel.setReturnMsg(entity);
        return resqModel;
    }
}

 

### HttpUtil 工具类概述 HttpUtil 是用于简化 HTTP 请求操作的 Java 实用程序库。该工具类提供了便捷的方法来执行常见的 HTTP 操作,如 GET 和 POST 请求,并且集成了多种功能特性以增强其灵活性和可靠性[^1]。 ### 功能特点 - **超时设置**:允许开发者指定连接和读取数据的最大等待时间。 - **URL 参数处理**:能够方便地构建带有查询字符串的 URL 地址。 - **请求体格式选择**:支持不同的内容类型,特别是 JSON 格式的请求体。 - **异常处理机制**:内置了对可能出现错误情况的有效管理策略。 - **日志记录能力**:可以跟踪并记录每次网络交互过程中的重要事件。 ### Maven 依赖配置 为了使用基于 HttpClient 的 HttpUtil 类,在项目中需添加如下 Maven 依赖: ```xml <dependency> <groupId>com.seepine</groupId> <artifactId>httpclient</artifactId> <version>1.0.0</version> </dependency> ``` ### 示例代码展示 #### 发送简单的 GET 请求 下面是一个利用 HttpUtil 执行 GET 方法的例子,其中包含了如何定义目标地址以及获取响应结果的过程。 ```java public String sendGetRequest(String url) { try { HttpResponse response = HttpUtil.createGet(url).execute(); return response.body(); } catch (Exception e) { logger.error("Error occurred while sending get request", e); throw new RuntimeException(e.getMessage()); } } ``` #### 提交包含 JSON 数据的 POST 请求 此部分展示了怎样通过 PostMethod 对象发送携带 JSON 负载的数据到远程服务器端点上。 ```java public void doPostWithJsonBody(String url, Map<String, Object> params) throws Exception { HttpRequest request = HttpUtil.createPost(url) .header("Content-Type", "application/json") .body(JSON.toJSONString(params)); HttpResponse httpResponse = request.execute(); System.out.println(httpResponse.getStatusLine().getStatusCode() + ":" + httpResponse.body()); } ``` ### 日志与调试建议 当遇到问题时,启用详细的日志可以帮助定位具体原因。通常情况下,默认的日志级别可能不足以提供足够的诊断信息;因此推荐调整至更细粒度的日志输出模式以便更好地理解整个通信流程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值