单例模式使用httpclient发送请求

使用httpclient发送post和get请求时,需要实例化HttpClient实例,再调用httpClient.execute()方法,每次实例化HttpClient耗时较大,而且HttpClient实例不能共用,不利于大量的请求处理,考虑到HttpClient实例公用,可以采用单利模式进行处理。HttpClientUtil是处理http请求工具类,在这个工具类里面封装了post和get请求的处理逻辑

public class HttpClientUtil {
  private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
  
  private CloseableHttpClient httpClient = null;
  private RequestConfig requestConfig = null;
  
  private static final HttpClientUtil HTTP_CLIENTUTIL = new HttpClientUtil();
  
  /**
   * 私有构造函数,禁止在外面new一个实例对象
   * 初始化httpClient实例和requestConfig配置信息
   */
  private HttpClientUtil() {
    httpClient = HttpClients.custom().disableAutomaticRetries().build();;
    requestConfig = RequestConfig.custom().setConnectionRequestTimeout(10000)
        .setSocketTimeout(10000).setConnectTimeout(10000).build();// 设置超时时间
  }
  
  /**
   * 对外暴露获取实例的接口
   * @return
   */
  public synchronized static HttpClientUtil getInstance() {
    return HTTP_CLIENTUTIL;
  }

上面的代码通过单利模式生成HttpClientUtil实例,并且初始化Httpclient

紧接着开始处理post和get请求:

/**
   * 处理request请求
   * 
   * @param request
   * @param jsonObj
   * @return
   * @throws Exception
   */
  public RpcResponse doWithRequest(RpcRequest request, JSONObject jsonObj) throws Exception {
    RpcResponse rpcResponse = new RpcResponse();
    rpcResponse.setRequestId(request.getRequestId());
    StringBuffer url = disposeUrl(request);

    try {

      HttpResponse response = null;

      if (request.getExecutorApiType().equalsIgnoreCase("GET")) {
        response = doGet(url);

      } else if (request.getExecutorApiType().equalsIgnoreCase("POST")) {
        response = doPost(jsonObj, url);
      }
      if (null != response) {
        StatusLine statusLine = response.getStatusLine();
        rpcResponse.setCode(statusLine.getStatusCode());
        rpcResponse.setResult(statusLine.toString() + ";请求路径:" + url.toString());
      }
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
      throw e;
    }
    return rpcResponse;
  }

  /**
   * 处理post请求
   * 
   * @param jsonObj
   * @param url
   * @return
   * @throws IOException
   * @throws ClientProtocolException
   */
  private HttpResponse doPost(JSONObject jsonObj, StringBuffer url)
      throws IOException, ClientProtocolException {
    HttpPost httpPost = new HttpPost(url.toString());
    httpPost.setConfig(this.requestConfig);

    // 构建消息实体
    if (jsonObj != null) {
      StringEntity entity = new StringEntity(jsonObj.toString(), Charset.forName("UTF-8"));
      entity.setContentEncoding("UTF-8");
      // 发送Json格式的数据请求
      entity.setContentType("application/json");
      httpPost.setEntity(entity);
    }
    // do post
    try(CloseableHttpResponse response = httpClient.execute(httpPost)){
      return response;
    } finally {
      httpPost.releaseConnection();
    }
  }


  /**
   * 处理get请求
   * 
   * @param url
   * @return
   * @throws IOException
   * @throws ClientProtocolException
   */
  private HttpResponse doGet(StringBuffer url) throws IOException, ClientProtocolException {
    HttpGet httpGet = new HttpGet(url.toString());
    httpGet.setConfig(this.requestConfig);
    httpGet.addHeader("token", "testToken");
    // do get
    try(CloseableHttpResponse response = httpClient.execute(httpGet)){
      return response;
    } finally {
      httpGet.releaseConnection();
    }
  }


  /**
   * 拼接url
   * 
   * @param request
   * @return
   */
  private static StringBuffer disposeUrl(RpcRequest request) {
    StringBuffer url = new StringBuffer();
    //api路径以http开头,不走网关直接使用该路径
    //否则请求需要走网关转发
    if (!request.getExecutorApiPath().toLowerCase().startsWith("http")) {
      if (!request.getGatewayAddress().toLowerCase().startsWith("http")) {
        url.append("http://");
      }
      url.append(request.getGatewayAddress() + "/services");
      
      if (!request.getExecutorApiPath().startsWith("/")) {
        url.append("/");
      }
    }
    url.append(request.getExecutorApiPath());
    
    return url;
  }

外部调用方式:

  public static void main(String[] args) {

    RpcRequest request = new RpcRequest();
    String jsonMessage = "{\"key\":\"语文\",\"value\":\"78\"}";
    JSONObject myJson = (JSONObject) JSON.parse(jsonMessage);
    
    HttpClientUtil httpClientUtil = HttpClientUtil.getInstance();
    RpcResponse response = httpClientUtil.doWithRequest(request, myJson);
 
  }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值