1. 程式人生 > >單例模式使用httpclient傳送請求

單例模式使用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);
 
  }