OkHttp的探索

我们知道,要完成一次网络请求,需要发送request和接收response,正常情况下当我们使用正常的http协议时,其中涉及到了建立连接,维护连接,缓存处理以及cookie处理等问题,这就显得很麻烦了。
索性,OkHttp将其封装好,为我们解决了大部分问题,下面我们就来看看如何使用OkHttp进行网络请求的发送。
OkHttp将http的请求过程封装为一个Call类,Call的接口代码如下:

/**
 * A call is a request that has been prepared for execution. A call can be canceled. As this object
 * represents a single request/response pair (stream), it cannot be executed twice.
 */
public interface Call extends Cloneable {

  Request request();

  void enqueue(Callback responseCallback);

  void cancel();

  boolean isExecuted();

  boolean isCanceled();

  /**
   * Create a new, identical call to this one which can be enqueued or executed even if this call
   * has already been.
   */
  Call clone();

  interface Factory {
    Call newCall(Request request);
  }
}

其中,Factory是他的工厂类,每次使用OkHttp的时候都要使用它。

我们可以对接口进行尝试调用,先尝试最基本的GET

private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
    Request request = new Request.Builder()
        .url("http://www.mx.com/tryGET") .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

    Headers responseHeaders = response.headers();
    for (int i = 0; i < responseHeaders.size(); i++) {
    }
}

第一行代码实现了Call.Factory接口, 是Call的工厂类, Call负责发送执行请求和读取响应.
enqueue()方法是为了维护请求队列,暂时还用不到。
cancel()取消请求, clone()能够对请求进行复用。
然后试用POST提交表单

 private final OkHttpClient client = new OkHttpClient();

  public void run() throws Exception {
    RequestBody formBody = new FormBody.Builder()
        .add("name", "ClassOne")
        .build();
    Request request = new Request.Builder()
        .url("https://westore.chenhaonee.cn/goodsDetail")
        .post(formBody)
        .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
  }

至此,我可以说已经找到了一种比较方便的方法进行网络请求

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,932评论 25 709
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,087评论 19 139
  • 这篇文章主要讲 Android 网络请求时所使用到的各个请求库的关系,以及 OkHttp3 的介绍。(如理解有误,...
    小庄bb阅读 1,240评论 0 4
  • 前言 在Android开发中,网络请求十分常用 而在Android网络请求库中,Retrofit是当下最热的一个网...
    Carson带你学安卓阅读 70,989评论 48 393
  • 中医认为,“湿气”是引发及恶化疾病的关键。因为环境和饮食习惯、生活习惯等因素,每个人体内都会有不同程度的湿气。 湿...
    了哥王阅读 730评论 0 0