1. 程式人生 > >okhttp 實現非同步請求

okhttp 實現非同步請求

四個工具類

① HttpCallback

public class HttpCallback implements Callback {
  private static Logger log = LoggerFactory.getLogger("netLog");

  private int successEventType;
  private int failureEventType;
  private long itemId;

  @Override
  public void onFailure(Call call, IOException e) {
    log.error("send http request fail. offer id {}, url {}", itemId, call.request().url().toString());
    log.error("send http request fail reason !", e);
//    EventBus.getInstance().push(failureEventType, itemId, null);
    HttpCallBackPool.getInstance().release(this);
  }

  @Override
  public void onResponse(Call call, Response response) throws IOException {
    HttpResponse httpResponse = buildHttpResponse(response);
//    EventBus.getInstance().push(successEventType, itemId, httpResponse);
    HttpCallBackPool.getInstance().release(this);
  }

  private HttpResponse buildHttpResponse(Response response) {
    HttpResponse httpResponse = new HttpResponse();
    httpResponse.setRequest(response.request());
    httpResponse.setCode(response.code());
    httpResponse.setLocation(response.header("Location"));
    httpResponse.setContentType(response.body().contentType());
    httpResponse.setRefresh(response.header("Refresh"));
    try {
      httpResponse.setBody(response.body().string());
    } catch (IOException e) {
      log.error("get response body fail. url: {}", response.request().url().toString());
      httpResponse.setBody("");
    }
    return httpResponse;
  }

  public void setItemId(long itemId) {
    this.itemId = itemId;
  }

  public void setSuccessEventType(int successEventType) {
    this.successEventType = successEventType;
  }

  public void setFailureEventType(int failureEventType) {
    this.failureEventType = failureEventType;
  }
}

②,HttpCallBackPool

public class HttpCallBackPool {
  private static HttpCallBackPool instance = new HttpCallBackPool();
  private static Logger log = LoggerFactory.getLogger(HttpCallBackPool.class);

  private Queue<HttpCallback> inactive = new LinkedList<>();

  private HttpCallBackPool() {
  }

  public static HttpCallBackPool getInstance() {
    return instance;
  }

  /**
   * 獲取一個HttpCallBack
   *
   * @return
   */
  public HttpCallback allocate(long itemId, int successEventType, int failureEventType) {
    HttpCallback httpCallback = inactive.poll();
    if (httpCallback == null) {
      httpCallback = new HttpCallback();
    }
    httpCallback.setItemId(itemId);
    httpCallback.setSuccessEventType(successEventType);
    httpCallback.setFailureEventType(failureEventType);
    return httpCallback;
  }

  /**
   * 釋放HttpCallBack
   *
   * @param
   */
  public void release(HttpCallback httpCallback) {
//    httpCallback.setItemId(EventBus.INVALID_ITEM_ID);
    inactive.add(httpCallback);
    log.info("httpCallbackPool size: {}", inactive.size());
  }

}

③,HttpResponse

public class HttpResponse {
  /**
   * 該response對應的request
   */
  private Request request;

  /**
   * 返回的狀態碼
   */
  private int code;

  /**
   * 跳轉連結
   */
  private String location;

  /**
   * 返回的型別
   */
  private MediaType contentType;

  /**
   * 返回的內容
   */
  private String body;

  /**
   * Refresh頭部內容
   */
  private String refresh;

  public String getRefresh() {
    return refresh;
  }

  public void setRefresh(String refresh) {
    this.refresh = refresh;
  }

  public Request getRequest() {
    return request;
  }

  public void setRequest(Request request) {
    this.request = request;
  }

  public int getCode() {
    return code;
  }

  public void setCode(int code) {
    this.code = code;
  }

  public boolean isRedirect() {
    switch (code) {
      case HTTP_PERM_REDIRECT:
      case HTTP_TEMP_REDIRECT:
      case HTTP_MULT_CHOICE:
      case HTTP_MOVED_PERM:
      case HTTP_MOVED_TEMP:
      case HTTP_SEE_OTHER:
        return true;
      default:
        return false;
    }
  }

  public boolean isSuccessful() {
    return code >= 200 && code < 400;
  }

  public String getLocation() {
    return location;
  }

  public void setLocation(String location) {
    this.location = location;
  }

  public MediaType getContentType() {
    return contentType;
  }

  public void setContentType(MediaType contentType) {
    this.contentType = contentType;
  }

  public String getBody() {
    return body;
  }

  public void setBody(String body) {
    this.body = body;
  }
}

④,OKHttpUtil

public class OKHttpUtil {

  private OKHttpUtil() {}
  private static OKHttpUtil instance = new OKHttpUtil();
  public static OKHttpUtil getInstance() {
    return instance;
  }
  
  private OkHttpClient httpClient = new OkHttpClient().newBuilder().followRedirects(false).build();  
  
  public void enqueue(String url, Callback callBack) {
    enqueue(url, callBack, null);
  }
  
  public void enqueue(String url, Callback callBack, Map<String, String> headers) {
    Builder builder = new Request.Builder().url(url);
    if(!CollectionUtils.isEmpty(headers)) {
      for(String key : headers.keySet()) {
        builder = builder.addHeader(key, headers.get(key));
      }
    }
    Request request = builder.build();
    httpClient.newCall(request).enqueue(callBack);
  }
}