java使用Httpclient发送post和get请求

做项目的时候需要使用到远程调用某个接口,采用简单的httpclient是一个不错的选择;采用http发送请求最核心的代码是httpClient.execute(httpPost)
下面是我项目中使用的工具类HttpClientUtil ,可以直接进行调用

/**
 * httpclient util 处理http请求工具类
 * 
 * @author administrator
 */
public class HttpClientUtil {
  private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

  private final CloseableHttpClient httpClient;
  private final RequestConfig requestConfig;

  public HttpClientUtil(CloseableHttpClient httpClient, RequestConfig requestConfig) {
    this.httpClient = httpClient;
    this.requestConfig = requestConfig;
  }


  /**
   * 处理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;
    } finally {
      try {
        httpClient.close();
      } catch (IOException e) {
        logger.error(e.getMessage(), e);
      }
    }
    return rpcResponse;
  }

  /**
   * 处理post请求
   * 
   * @param jsonObj
   * @param url
   * @return
   * @throws IOException
   * @throws ClientProtocolException
   */
  private HttpResponse doPost(JSONObject jsonObj, StringBuffer url)
      throws IOException, ClientProtocolException {
    HttpResponse response;
    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 {
      response = httpClient.execute(httpPost);
    } finally {
      httpPost.releaseConnection();
    }
    return response;
  }


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


  /**
   * 拼接url
   * 
   * @param request
   * @return
   */
  private static StringBuffer disposeUrl(RpcRequest request) {
    StringBuffer url = new StringBuffer();
    if (!request.getGatewayAddress().startsWith("http")) {
      url.append("http://");
    }
    url.append(request.getGatewayAddress() + "/services");

    if (!request.getExecutorApiPath().startsWith("/")) {
      url.append("/");
    }
    url.append(request.getExecutorApiPath());
    return url;
  }
}

写一个main函数进行调用

public static void main(String[] args) {
    RpcRequest request = new RpcRequest();
    JSONObject jsonObj = request.getParameters();

    CloseableHttpClient httpClient = HttpClients.custom().disableAutomaticRetries().build();
    RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(10000)
        .setSocketTimeout(10000).setConnectTimeout(10000).build();// 设置超时时间

    HttpClientUtil httpClientUtil = new HttpClientUtil(httpClient, requestConfig);
    RpcResponse response = httpClientUtil.doWithRequest(request, jsonObj);

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值