OkHttp3学习(一):基本使用

An HTTP & HTTP/2 client for Android and Java applications
引用自官方文档java

什么都无论,先上个代码。敲完再说。git

GET

OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .get()
                .url(PATH)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String string = response.body().string();
                    Log.i(TAG, "onResponse: "+string);
                }
            }
        });

clipboard.png

上面的图中显示了response.body()能够获得的数据类型。在上面的例子中咱们使用了string()来获得了相应的字符串数据。
须要注意的是这里的回调不在主线程.若是须要更新UI。咱们还须要切换到主线程进行操做。github

POST

这是一个异步调用的例子。json

MediaType jsonType = MediaType.parse("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient();
        String jsonStr = new Gson().toJson(mPerson);
        RequestBody body = RequestBody.create(jsonType,jsonStr);
        Request request = new Request.Builder()
                .post(body)
                .url(PATH)
                .build();
        client.newCall(request).enqueue(new Callback() {
           @Override
           public void onFailure(Call call, IOException e) {
           }

           @Override
           public void onResponse(Call call, Response response) throws IOException {
               if (response.isSuccessful()){
                   String string = response.body().string();
                   Log.i(TAG, "post: "+string);
               }
           }
        });

请求大体过程

咱们每次作请求的时候都要有一个OkHttpClient实体,用来构建咱们的一次请求。而Request类用来设置咱们请求须要的参数,以后咱们就能够经过client来发送一个请求了。在上面的例子中,咱们将请求加入到了一个请求队列中(enqueue)。最后咱们就获得了此次请求的响应response了。设计模式

Request

在构建Request的时候,使用到了Builder设计模式。只须要简单的链式调用配置好请求参数。以下:app

Request request = new Request.Builder().url(PATH)
                .header("User-Agent", "my-agent")
                .addHeader("Accept-Language", "zh-cn")
                .get()
                .build();

header && addHeader

headeraddHeader用来添加头部字段的key-value对。异步

/**
     * Sets the header named {@code name} to {@code value}. If this request already has any headers
     * with that name, they are all replaced.
     */
    public Builder header(String name, String value) {
      headers.set(name, value);
      return this;
    }
    /**
     * Adds a header with {@code name} and {@code value}. Prefer this method for multiply-valued
     * headers like "Cookie".
     *
     * <p>Note that for some headers including {@code Content-Length} and {@code Content-Encoding},
     * OkHttp may replace {@code value} with a header derived from the request body.
     */
    public Builder addHeader(String name, String value) {
      headers.add(name, value);
      return this;
    }

咱们看到,这两个函数底层一个是使用的Header.Builderset(),一个是使用的add().在继续往里看:ide

/**
     * Set a field with the specified value. If the field is not found, it is added. If the field is
     * found, the existing values are replaced.
     */
    public Builder set(String name, String value) {
      checkNameAndValue(name, value);
      removeAll(name);
      addLenient(name, value);
      return this;
    }
    
      /** Add a field with the specified value. */
    public Builder add(String name, String value) {
      checkNameAndValue(name, value);
      return addLenient(name, value);
    }

这就很清晰了。很明显了。set()调用了removeAll(key)方法来删除以前设置了同名的key。而add并无删除。其实从名字咱们就能够看出来。add就是添加嘛。set设置,确定只有一个嘛。函数

RequestBody

OkHttpClient client =new OkHttpClient();
        MediaType parse = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(parse,new Gson().toJson(mPerson));
        Request request = new Request.Builder().url(PATH)
                .header("User-Agent", "my-agent")
                .addHeader("Accept-Language", "zh-cn")
                .post(body)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

            }
        });

将上面的请求经过抓包工具抓取后,下图即为本次的请求。
clipboard.png工具

ResponseBody是一个抽象类。在okhttp中的子类有FormBodyMultipartBody。 咱们能够经过静态方法create来构建一个ResponseBody

clipboard.png

ResponseBody内部的create能够经过三中方式构建。固然了。咱们也能够模仿官方的crete方法来构建本身的
ResponseBody来上传制定类型的文件。
咱们经过MediaType来指定咱们上传文件的类型。好比上面代码中的"application/json; charset=utf-8"就是咱们上传的内容的类型。
当咱们有什么文件想要提交,可是不知道key是什么的时候能够看MIME 参考手册

FormBody

用来提交一些表单数据。经过FormBody.Builder来添加表单数据。以下所示:

OkHttpClient client = new OkHttpClient();
        FormBody formBody = new FormBody.Builder()
                .add("username", "jason")
                .add("password", "magicer")
                .build();
        Request request = new Request.Builder()
                .post(formBody)
                .addHeader("User-Agent", "Apple")
                .build();
        Response response = client.newCall(request).execute();

FromBody中,查看其源码咱们能够看到FormBody设置的Content-Type"application/x-www-form-urlencoded".也就是普通表单数据。

private static final MediaType CONTENT_TYPE =
      MediaType.parse("application/x-www-form-urlencoded");

MultipartBody

如下是MultipartBody中的一些个类型。

public static final MediaType MIXED = MediaType.parse("multipart/mixed");
public static final MediaType ALTERNATIVE = MediaType.parse("multipart/alternative");
public static final MediaType DIGEST = MediaType.parse("multipart/digest");
public static final MediaType PARALLEL = MediaType.parse("multipart/parallel");
public static final MediaType FORM = MediaType.parse("multipart/form-data");
相关文章
相关标签/搜索