美文网首页
OkHttp的探索

OkHttp的探索

作者: 沉默的舞者 | 来源:发表于2017-06-13 22:57 被阅读0次

    我们知道,要完成一次网络请求,需要发送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);
      }
    

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

    相关文章

      网友评论

          本文标题:OkHttp的探索

          本文链接:https://www.haomeiwen.com/subject/mkvjqxtx.html