【Http请求工具类】

Http请求工具类(待优化)

  1. 添加相关依赖
        <!-- 发送http请求依赖 -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.10</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
            <exclusions>
                <exclusion>
                    <artifactId>httpcore</artifactId>
                    <groupId>org.apache.httpcomponents</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>
  1. 创建请求响应体
/**
 1. @author 苏育科
 2. @date 2020/07/11 12:20
 */
@Data
public class HttpResponseEntity {

    /**
     * 响应结果(字符串)
     */
    private String reponseStr;

    /**
     * 响应码
     */
    private int reponseCode;

    /**
     * 响应头
     */
    private String header;

    /**
     * 无参构造
     */
    public HttpResponseEntity() {
    }

    /**
     * 有参构造
     *
     * @param reponseStr  响应内容字符串
     * @param reponseCode 响应码
     */
    public HttpResponseEntity(String reponseStr, int reponseCode) {
        this.reponseStr = reponseStr;
        this.reponseCode = reponseCode;
    }

    /**
     * 有参构造
     *
     * @param reponseStr  响应内容字符串
     * @param reponseCode 响应码
     * @param header      响应头
     */
    public HttpResponseEntity(String reponseStr, int reponseCode, String header) {
        this.reponseStr = reponseStr;
        this.reponseCode = reponseCode;
        this.header = header;
    }
}
  1. 创建请求常量
/**
 1. @author 苏育科
 2. @date 2020-11-20 10:08:11
 3. @describe:
 */
public interface HttpConstant {

    /**
     * get请求
     */
    String GET = "GET";

    /**
     * options请求
     */
    String OPTIONS = "OPTIONS";

    /**
     * POST请求
     */
    String POST = "POST";

    /**
     * POST请求
     */
    String DELETE = "DELETE";

    /**
     * POST请求
     */
    String PUT = "PUT";

    /**
     * http请求等待最长时间/ms
     */
    int TIMEOUT = 6000;
}

4.创建请求工具类
目前只支持get和post轮询,因为delete和put用的少所有没有
get、post这两个请求的请求参数是JsonObject类型
delete、put这两个请求的请求参数是Map类型

详见代码:

/**
 1. @author 苏育科
 2. @date 2020/07/11 12:18
 */
@Slf4j
public class HttpUtils {

    /**
     * 发送GET请求
     *
     * @param url       请求路径
     * @param jsonParam 请求参数 可以为NULL
     * @param header    请求头 可以为NULL
     * @return 请求响应体
     */
    public static HttpResponseEntity get(String url, JSONObject jsonParam, Map<String, String> header) throws Exception {

        //1.创建请求连接
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //2.拼接参数进入URL
        if (null != jsonParam && 0 != jsonParam.size()) {
            url = addParamToUrl(url, jsonParam);
        }

        //3.创建GET请求
        HttpGet httpGet = new HttpGet(url);
        RequestConfig requestConfig = RequestConfig
                .custom()
                .setConnectTimeout(HttpConstant.TIMEOUT)
                .setConnectionRequestTimeout(HttpConstant.TIMEOUT)
                .setSocketTimeout(HttpConstant.TIMEOUT)
                .build();
        httpGet.setConfig(requestConfig);

        //4.设置请求头
        if (null != header) {
            for (Map.Entry<String, String> entry : header.entrySet()) {
                httpGet.addHeader(entry.getKey(), entry.getValue());
            }
        }

        //5.发送请求
        HttpResponseEntity httpResponseEntity;
        try {
            HttpResponse response = httpClient.execute(httpGet);
            httpResponseEntity = getHttpResponseEntity(response);
            log.info("URL:[{}],请求参数:[{}],响应结果:{}", url, jsonParam, httpResponseEntity);

            return httpResponseEntity;
        } finally {
            httpClient.close();
        }
    }

    /**
     * 发送POST请求
     *
     * @param url    请求路径
     * @param data   请求参数 可以为NULL
     * @param header 请求头 可以为NULL
     * @return 请求响应体
     */
    public static JSONObject post(String url, NameValuePair[] data, HashMap<String, String> header) throws Exception {

        //1.创建请求连接
        HttpClient httpClient = new HttpClient();
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(HttpConstant.TIMEOUT);
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(HttpConstant.TIMEOUT);
        httpClient.getParams().setParameter("http.protocol.content-charset", "UTF-8");

        //2.创建请求连接并创建POST请求
        PostMethod postMethod = new PostMethod(url);

        //3.设置请求头
        if (null != header) {
            for (Map.Entry<String, String> entry : header.entrySet()) {
                postMethod.setRequestHeader(entry.getKey(), entry.getValue());
            }
        }

        //4.设置请求参数
        if (null != data) {
            postMethod.setRequestBody(data);
        }

        //5.发送请求
        try {
            httpClient.executeMethod(postMethod);
            String resultStr = postMethod.getResponseBodyAsString();
            JSONObject result = JSONObject.parseObject(resultStr);
            log.info("URL:[{}],请求参数:[{}],响应结果:{}", url, data, result);

            return result;
        } finally {
            postMethod.releaseConnection();
        }
    }

    /**
     * 发送POST请求
     *
     * @param url    请求路径
     * @param data   请求参数 可以为NULL
     * @param header 请求头 可以为NULL
     * @return 请求响应体
     */
    public static JSONObject post(String url, JSONObject data, HashMap<String, String> header) throws Exception {

        //1.创建请求连接
        HttpClient httpClient = new HttpClient();
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(HttpConstant.TIMEOUT);
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(HttpConstant.TIMEOUT);
        httpClient.getParams().setParameter("http.protocol.content-charset", "UTF-8");

        //2.拼接参数进入URL
        if (null != data && 0 != data.size()) {
            url = addParamToUrl(url, data);
        }

        //3.创建请求连接并创建POST请求
        PostMethod postMethod = new PostMethod(url);

        //4.设置请求头
        if (null != header) {
            for (Map.Entry<String, String> entry : header.entrySet()) {
                postMethod.setRequestHeader(entry.getKey(), entry.getValue());
            }
        }

        //5.发送请求
        try {
            httpClient.executeMethod(postMethod);
            String resultStr = postMethod.getResponseBodyAsString();
            JSONObject result = JSONObject.parseObject(resultStr);
            log.info("URL:[{}],请求参数:[{}],响应结果:{}", url, data, result);

            return result;
        } finally {
            postMethod.releaseConnection();
        }
    }

    /**
     * 发送DELETE请求
     *
     * @param url            请求地址
     * @param headers        请求头
     * @param params         请求参数
     * @return
     * @throws Exception
     */
    public static Object delete(String url, Map<String, String> headers, Map<String, String> params) throws Exception {

        //1.创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //2.拼接PUT请求URL
        URIBuilder uriBuilder = new URIBuilder(url);
        if (params != null) {
            Set<Map.Entry<String, String>> entrySet = params.entrySet();
            for (Map.Entry<String, String> entry : entrySet) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue());
            }
        }

        //3.创建httpPut对象
        HttpDelete httpDelete = new HttpDelete(uriBuilder.build());

        //4.设置请求时间和响应时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(HttpConstant.TIMEOUT)
                .setConnectionRequestTimeout(HttpConstant.TIMEOUT)
                .setSocketTimeout(HttpConstant.TIMEOUT)
                .build();
        httpDelete.setConfig(requestConfig);

        //5.设置请求头
        packageHeader(headers, httpDelete);

        //6.创建httpResponse对象,发送请求
        CloseableHttpResponse httpResponse = null;
        try {
            Object result = getHttpClientResult(httpResponse, httpClient, httpDelete);

            log.info("[DELETE请求] URL[{}],请求头[{}],请求参数[{}],连接超时时间[{}],响应超时时间[{}]", url, headers, params);
            log.info("[DELETE请求] 响应结果[{}]", result);
            return result;
        } finally {
            release(httpResponse, httpClient);
        }
    }

    /**
     * 发送PUT请求
     *
     * @param url            请求地址
     * @param headers        请求头
     * @param params         请求参数
     * @return
     * @throws Exception
     */
    public static Object put(String url, Map<String, String> headers, Map<String, Object> params) throws Exception {

        //1.创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //2.创建httpPut对象
        HttpPut httpPut = new HttpPut(url);

        //3.设置请求时间和响应时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(HttpConstant.TIMEOUT)
                .setConnectionRequestTimeout(HttpConstant.TIMEOUT)
                .setSocketTimeout(HttpConstant.TIMEOUT)
                .build();
        httpPut.setConfig(requestConfig);

        //4.设置请求头
        packageHeader(headers, httpPut);

        //5.设置请求参数
        packageParam(params, httpPut);

        //6.创建httpResponse对象,发送请求
        CloseableHttpResponse httpResponse = null;
        try {
            Object result = getHttpClientResult(httpResponse, httpClient, httpPut);

            log.info("[PUT请求] URL[{}],请求头[{}],请求参数[{}],连接超时时间[{}],响应超时时间[{}]", url, headers, params);
            log.info("[PUT请求] 响应结果[{}]", result);
            return result;
        } finally {
            release(httpResponse, httpClient);
        }
    }

    /**
     * 递归请求(失败递归)
     * 目前只支持get和post轮询,因为delete和put用的少所有没有,而且这两的请求参数是Map类型的
     * @param round    当前轮次
     * @param url      请求路径
     * @param title    日志标题
     * @param method   方法
     * @param param    请求参数
     * @param response 请求响应
     */
    public static Object recursive(int round, String url, String title, String method, JSONObject param, Object response) {

        //1.如果轮次大于指定轮次
        if (round > 3) {
            return response;
        }

        //2.发送请求
        log.info("[server] {} 第{}次轮询 请求参数:[{}]", title, round, param);
        try {
            response = HttpConstant.GET.equals(method) ? HttpUtils.get(url, param, null) : HttpUtils.post(url, param, null);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //3.如果response为空,代表请求失败,继续轮询请求
        if (null == response) {
            round++;
            recursive(round, url, title, method, param, response);
        }

        return response;
    }

    /**
     * Description: 封装请求头
     *
     * @param headers    请求头
     * @param httpMethod 请求HTTP方法
     */
    private static void packageHeader(Map<String, String> headers, HttpRequestBase httpMethod) {
        if (headers != null) {
            Set<Map.Entry<String, String>> entrySet = headers.entrySet();
            for (Map.Entry<String, String> entry : entrySet) {
                httpMethod.setHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    /**
     * Description: 封装请求参数
     *
     * @param params     请求参数
     * @param httpMethod 请求方法
     */
    private static void packageParam(Map<String, Object> params, HttpEntityEnclosingRequestBase httpMethod) {
        if (params != null) {
            JSONObject jsonObject = new JSONObject(true);
            Set<String> strings = params.keySet();
            for (String string : strings) {
                jsonObject.put(string, params.get(string));
            }
            StringEntity strParam = new StringEntity(jsonObject.toJSONString(), "UTF-8");
            httpMethod.setEntity(strParam);
        }
    }

    /**
     * Description: 获得响应结果
     *
     * @param httpResponse
     * @param httpClient
     * @param httpMethod
     * @return
     * @throws Exception
     */
    private static Object getHttpClientResult(CloseableHttpResponse httpResponse,
                                                  CloseableHttpClient httpClient,
                                                  HttpRequestBase httpMethod) throws Exception {
        String content = "";
        //1.执行http请求
        httpResponse = httpClient.execute(httpMethod);
        //2.获取返回结果
        if (httpResponse != null && httpResponse.getStatusLine() != null) {
            if (httpResponse.getEntity() != null) {
                content = EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
            }
            return  content;
        }
        return content;
    }

    /**
     * Description: 释放资源
     *
     * @param httpResponse
     * @param httpClient
     * @throws IOException
     */
    private static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {
        if (httpResponse != null) {
            httpResponse.close();
        }
        if (httpClient != null) {
            httpClient.close();
        }
    }

    /**
     * 添加参数到URL
     *
     * @param url       请求URL
     * @param jsonParam 请求参数
     * @return 拼接参数的URL
     */
    private static String addParamToUrl(String url, JSONObject jsonParam) {
        StringBuilder urlSb = new StringBuilder(url);

        int i = 0;
        for (String key : jsonParam.keySet()) {
            if (i == 0) {
                urlSb.append("?");
            }
            urlSb.append(key.trim()).append("=").append(jsonParam.get(key).toString().trim()).append("&");
            i++;
        }

        url = urlSb.deleteCharAt(urlSb.length() - 1).toString();
        return url;
    }

    /**
     * 解析HttpResponse
     *
     * @param response http响应
     * @return HttpResponseEntity 响应体
     * @throws Exception IO异常
     */
    private static HttpResponseEntity getHttpResponseEntity(HttpResponse response) throws Exception {
        HttpResponseEntity httpResponseEntity;
        //5.1 获取响应码
        int responseCode = response.getStatusLine().getStatusCode();

        //5.2 获取响应结果
        String reponseStr = new String();
        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String lines;
        while ((lines = reader.readLine()) != null) {
            lines = new String(lines.getBytes(), "utf-8");
            reponseStr += lines;
        }

        //5.3 封装
        httpResponseEntity = new HttpResponseEntity(reponseStr, responseCode);
        return httpResponseEntity;
    }
}
  1. 具体用法
/**
     * 增加经验
     *
     * @param uid     角色id
     * @param exp     经验值
     * @param worldId   组号id
     */
    public static JSONObject addCharacterExp(String uid, Integer exp, String worldId) {

        //1.设置请求参数
        JSONObject param = new JSONObject();
        param.put("uid", uid);
        param.put("exp", exp);

        //2.发送请求
        Object response = null;
        String url = MjServerUtils.urlConfig.getServerAddCharacterExpInfoMap().get(worldId);
        response = HttpUtils.recursive(1, url, "增加经验", HttpConstant.POST, param, response);

        //3.请求失败,返回null
        if (null == response) {
            log.info("[server] 增加经验 请求失败 请求参数:[{}] 响应:[{}]", param, response);
            return null;
        }

        //4.请求成功返回JSON结果
        log.info("[server] 增加经验 请求成功 请求参数:[{}] 响应:[{}]", param, response);
        return JSONObject.parseObject(JSONObject.toJSONString(response));
    }
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值