HttpClientUtil

package com.ykt.ffan.common.http;


import java.util.Date;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ykt.ffan.common.utils.StringUtil;

import lombok.extern.slf4j.Slf4j;



/**
 * @author: lvyong6
 */
@Slf4j
public class HttpClientUtil {
    private static String charset = "UTF-8";

    public static String doGet(String path, Map<String, String> params) {
        return doCall(path, params, HttpMethod.GET);
    }

    public static String doPost(String path, Map<String, String> params, int httpClinetSoTimeout) {
       if(httpClinetSoTimeout>0) {
          params.put("httpClinetSoTimeout", httpClinetSoTimeout+"");
       }
        return doCall(path, params, HttpMethod.POST);
    }

    private static String doCall(String path, Map<String, String> params, HttpMethod method) {
        if (StringUtil.isBlank(path)) {
            throw new IllegalArgumentException("Parameter 'path' is empty.");
        }

        Date startTime = new Date();
        // 构造request对象
        Request request = new Request();
        request.setGateway(path);
        request.setMethod(method);
        request.setCharset(charset);
        String httpClinetSoTimeout = params.get("httpClinetSoTimeout");
        
        if(null !=httpClinetSoTimeout) {
           request.setSoTimeout(Integer.parseInt(httpClinetSoTimeout));
        }
        if (params != null && !params.isEmpty()) {
            for (String key : params.keySet()) {
                request.addParam(key, params.get(key));
            }
        }
        Response response = HttpCaller.getInstance().call(request, null);
        Date endTime = new Date();
        if (response.isSuccess()) {
            response.setRespCharset(charset);
            String result = response.getStringResult();
            // 将结果输出到日志, 超出500字符进行截取
            StringBuffer sbf = new StringBuffer();
            if (result.length() > 500) {
                sbf.append(result.substring(0, 500));
                sbf.append("..omit..");
            } else {
                sbf.append(result);
            }
            long costtime = endTime.getTime() - startTime.getTime();
            log.info(String.format("调用服务 : %s; response text: %s\t costtime(ms) : %d", path, sbf.toString(),
                    costtime));
            return result;
        }

        return null;
    }

    public static String doGet(String path, Map<String, String> params, int connectionTimeout, int soTimeOut) {
        return doCall(path, params, HttpMethod.GET, connectionTimeout, soTimeOut, null);
    }

    public static String doPost(String path, Map<String, String> params, int connectionTimeout, int soTimeOut) {
        return doCall(path, params, HttpMethod.POST, connectionTimeout, soTimeOut, null);
    }

    public static String doGet(String path, Map<String, String> params, int connectionTimeout, int soTimeOut,
                               Integer retryCount) {
        return doCall(path, params, HttpMethod.GET, connectionTimeout, soTimeOut, retryCount);
    }

    public static String doPost(String path, Map<String, String> params, int connectionTimeout, int soTimeOut,
                                Integer retryCount) {
        return doCall(path, params, HttpMethod.POST, connectionTimeout, soTimeOut, retryCount);
    }

    private static String doCall(String path, Map<String, String> params, HttpMethod method, int connectionTimeout,
                                 int soTimeOut, Integer retryCount) {
        if (StringUtil.isBlank(path)) {
            throw new IllegalArgumentException("Parameter 'path' is empty.");
        }
        Date startTime = new Date();
        // 构造request对象
        Request request = new Request();
        request.setGateway(path);
        request.setMethod(method);
        request.setCharset(charset);
        request.setConnectionTimeout(connectionTimeout);
        request.setSoTimeout(soTimeOut);
        if (params != null && !params.isEmpty()) {
            for (String key : params.keySet()) {
                request.addParam(key, params.get(key));
            }
        }
        Response response = HttpCaller.getInstance().call(request, retryCount);
        Date endTime = new Date();
        if (response.isSuccess()) {
            response.setRespCharset(charset);
            String result = response.getStringResult();
            // 将结果输出到日志, 超出500字符进行截取
            StringBuffer sbf = new StringBuffer();
            if (result.length() > 500) {
                sbf.append(result.substring(0, 500));
                sbf.append("..omit..");
            } else {
                sbf.append(result);
            }
            long costtime = endTime.getTime() - startTime.getTime();
            log.info(String.format("调用服务 : %s; response text: %s\t costtime(ms) : %d", path, sbf.toString(),
                    costtime));
            return result;
        }

        return null;
    }
}
### HttpClientUtil 类使用示例 #### 工具类概述 `HttpClientUtils` 是一个封装了常用 HTTP 请求操作的工具类,基于 Apache HttpClient 实现。该工具类支持 GET、POST、PUT、DELETE 等常见的请求方法,并提供了请求头设置、参数传递、响应处理以及超时设置等功能[^1]。 #### Maven依赖配置 为了使用 `HttpClientUtils` 或者直接使用 Apache HttpClient 进行开发,项目中需要引入相应的 Maven 依赖: ```xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.5.13</version> </dependency> ``` #### 发送GET请求实例 下面是一个简单的发送 GET 请求并打印服务器返回内容的例子: ```java import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class HttpClientExample { public static void main(String[] args) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpGet request = new HttpGet("https://jsonplaceholder.typicode.com/posts/1"); // 执行GET请求 CloseableHttpResponse response = httpClient.execute(request); try { System.out.println(EntityUtils.toString(response.getEntity())); } finally { response.close(); } } finally { httpClient.close(); } } } ``` 此代码创建了一个默认的 `CloseableHttpClient` 对象来执行 HTTP 请求。通过构建 `HttpGet` 来指定目标 URL 并调用 `execute()` 方法发起请求。最后读取响应实体的内容并通过 `EntityUtils.toString()` 转换成字符串形式输出到控制台[^4]。 对于更复杂的场景,比如 POST 表单提交或者上传文件,则可以通过调整上述模板中的具体实现细节完成相应功能需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值