1. 程式人生 > >java使用Httpclient傳送post和get請求

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);

}