Java後端Http請求其他後端接口封裝工具類

Http請求工具類:包含,get,put,post(delete請求與get請求類似)

package com.construn.vehicleservice.util;

import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * @param
 * @return
 * @author chaosgod 2019-04-24 09:24
 * @description : Http請求
 */
@Slf4j
public class APIHttpClient {

  /** 接口地址 */
  private String apiURL;

  private HttpClient httpClient = null;
  private HttpPost httpPost = null;
  private HttpPut httpPut = null;
  private long startTime = 0L;
  private long endTime = 0L;
  private int status = 0;

  /**
   * 接口地址
   *
   * @param url
   */
  public APIHttpClient(String url) {
    if (url != null) {
      apiURL = url;
      httpClient = HttpClients.createDefault();
      httpPost = new HttpPost(apiURL);
      httpPut = new HttpPut(apiURL);
    }
  }

  /**
   * 調用 API
   *
   * @param parameters
   * @return
   */
  public String post(String parameters) {
    String body = null;
    log.info("parameters:{}", parameters);
    // 創建一個返回值對象
    if (httpPost != null & parameters != null && !"".equals(parameters.trim())) {
      try {
        // 建立一個NameValuePair數組,用於存儲欲傳送的參數
        httpPost.addHeader("Content-type", "application/json; charset=utf-8");
        httpPost.setHeader("Accept", "application/json");
        httpPost.setEntity(new StringEntity(parameters, Charset.forName("UTF-8")));
        startTime = System.currentTimeMillis();
        HttpResponse response = httpClient.execute(httpPost);
        endTime = System.currentTimeMillis();
        int statusCode = response.getStatusLine().getStatusCode();
        log.info("statusCode:" + statusCode);
        log.info("調用API:{} 花費時間(單位:毫秒):{}", httpPost.getURI(), (endTime - startTime));
        if (statusCode != HttpStatus.SC_OK) {
          log.error("httpPost failed:" + response.getStatusLine());
          status = 1;
        }
        // Read the response body
        body = EntityUtils.toString(response.getEntity());
      } catch (IOException e) {
        // 網絡錯誤
        status = 3;
        log.error("連接失敗,網絡錯誤");
      } catch (Exception e) {
        log.info("遇到錯誤");
      } finally {
        log.info("調用接口狀態:" + status);
      }
    }
    return body;
  }

  public String put(String parameters) {
    String body = null;
    log.info("parameters:{}", parameters);
    // 創建一個返回值對象
    if (httpPut != null & parameters != null && !"".equals(parameters.trim())) {
      try {
        // 建立一個NameValuePair數組,用於存儲欲傳送的參數
        httpPut.addHeader("Content-type", "application/json; charset=utf-8");
        httpPut.setHeader("Accept", "application/json");
        httpPut.setEntity(new StringEntity(parameters, Charset.forName("UTF-8")));
        startTime = System.currentTimeMillis();
        HttpResponse response = httpClient.execute(httpPut);
        endTime = System.currentTimeMillis();
        int statusCode = response.getStatusLine().getStatusCode();
        log.info("statusCode:" + statusCode);
        log.info("調用API:{} 花費時間(單位:毫秒):{}", httpPut.getURI(), (endTime - startTime));
        if (statusCode != HttpStatus.SC_OK) {
          log.error("httpPost failed:" + response.getStatusLine());
          status = 1;
        }
        // Read the response body
        body = EntityUtils.toString(response.getEntity());
      } catch (IOException e) {
        // 網絡錯誤
        status = 3;
        log.error("連接失敗,網絡錯誤");
      } catch (Exception e) {
        log.info("遇到錯誤");
      } finally {
        log.info("調用接口狀態:" + status);
      }
    }
    return body;
  }

  /**
   * 實現get請求
   *
   * @param baseUrl
   * @param parameters 傳入參數的map;當無參數時,傳入的map=null即可
   * @param headers 傳入header的map, 例如cookies等,當無值時,傳入null即可
   * @return
   */
  public String get(Map<String, String> parameters) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    String entityString = null;
    log.info("Url:{}", apiURL);
    log.info("parameters:{}", parameters);
    try {
      URIBuilder uriBuilder = new URIBuilder(apiURL);
      if (parameters != null && parameters.size() > 0) {
        for (Map.Entry<String, String> temp : parameters.entrySet()) {
          // 循環map裏面的每一對鍵值對,然後獲取key和value即時想要的參數的 key和value
          uriBuilder.addParameter(temp.getKey(), temp.getValue());
        }
      }
      HttpGet get = new HttpGet(uriBuilder.build());
      startTime = System.currentTimeMillis();
      response = httpClient.execute(get);
      endTime = System.currentTimeMillis();
      int statusCode = response.getStatusLine().getStatusCode();
      log.info("statusCode:" + statusCode);
      log.info("調用API:{} 花費時間(單位:毫秒):{}", get.getURI(), (endTime - startTime));
      if (statusCode != HttpStatus.SC_OK) {
        log.error("httpPost failed:" + response.getStatusLine());
        status = 1;
      }
      HttpEntity entity = response.getEntity();
      entityString = EntityUtils.toString(entity, "utf-8");
    } catch (URISyntaxException e) {
      e.printStackTrace();
    } catch (IOException e) {
      // 網絡錯誤
      status = 3;
      log.error("連接失敗,網絡錯誤");
    } finally {
      try {
        if (response != null) {
          response.close();
        }
        if (httpClient != null) {
          httpClient.close();
        }

      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return entityString;
  }

  /**
   * 0.成功 1.執行方法失敗 2.協議錯誤 3.網絡錯誤
   *
   * @return the status
   */
  public int getStatus() {
    return status;
  }

  /** @param status the status to set */
  public void setStatus(int status) {
    this.status = status;
  }

  /** @return the startTime */
  public long getStartTime() {
    return startTime;
  }

  /** @return the endTime */
  public long getEndTime() {
    return endTime;
  }
}

項目中使用Eg:

  public void overEmpWorkTask(Map<String, Object> map) throws VehicleException {
    String str;
    try {
      str = new APIHttpClient(overEmpWorkTask).post(JSONObject.toJSONString(map));
      log.info("獲得返回{}", str);
      JSONObject jsonObject = JSONObject.parseObject(str);
      if (!jsonObject.get("code").equals(ResponseObj.SUCCESS_CODE)) {
        throw new VehicleInterErrorException((String) jsonObject.get("userInfo"));
      }
    } catch (VehicleInterErrorException e) {
      throw e;
    } catch (Exception e) {
      throw new VehicleException("鏈接失敗");
    }
  }

如上代碼,服務實現類只需要調用overEmpWorkTask方法並且穿參Map,然後捕獲VehicleInterErrorException異常,拋出去,前端則會收到後端的後端拋出得異常信息;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章