okhttp3使用

一、引入包

在项目module下的build.gradle添加okhttp3依赖

compile ‘com.squareup.okhttp3:okhttp:3.3.1‘

二、基本使用

1、okhttp3 Get 方法

1.1 、okhttp3 同步 Get方法

/**
 * 同步Get方法
 */
private void okHttp_synchronousGet() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                String url = "https://api.github.com/";
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder().url(url).build();
                okhttp3.Response response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    Log.i(TAG, response.body().string());
                } else {
                    Log.i(TAG, "okHttp is request error");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();
}

Request是okhttp3 的请求对象,Response是okhttp3中的响应。通过response.isSuccessful()判断请求是否成功。

@Contract(pure=true)
public boolean isSuccessful()
Returns true if the code is in [200..300), which means the request was successfully received, understood, and accepted.

获取返回的数据,可通过response.body().string()获取,默认返回的是utf-8格式;string()适用于获取小数据信息,如果返回的数据超过1M,建议使用stream()获取返回的数据,因为string() 方法会将整个文档加载到内存中。

@NotNull
public final java.lang.String string()
                             throws java.io.IOException
Returns the response as a string decoded with the charset of the Content-Type header. If that header is either absent or lacks a charset, this will attempt to decode the response body as UTF-8.
Throws:
java.io.IOException

当然也可以获取流输出形式;

public final java.io.InputStream byteStream()

1.2 、okhttp3 异步 Get方法

有时候需要下载一份文件(比如网络图片),如果文件比较大,整个下载会比较耗时,通常我们会将耗时任务放到工作线程中,而使用okhttp3异步方法,不需要我们开启工作线程执行网络请求,返回的结果也在工作线程中;

/**
 * 异步 Get方法
 */
private void okHttp_asynchronousGet(){
    try {
        Log.i(TAG,"main thread id is "+Thread.currentThread().getId());
        String url = "https://api.github.com/";
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        client.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {

            }

            @Override
            public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
                // 注:该回调是子线程,非主线程
                Log.i(TAG,"callback thread id is "+Thread.currentThread().getId());
                Log.i(TAG,response.body().string());
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
}

注:Android 4.0 之后,要求网络请求必须在工作线程中运行,不再允许在主线程中运行。因此,如果使用 okhttp3 的同步Get方法,需要新起工作线程调用。

1.3 、添加请求头

okhttp3添加请求头,需要在Request.Builder()使用.header(String key,String value)或者.addHeader(String key,String value);

使用.header(String key,String value),如果key已经存在,将会移除该key对应的value,然后将新value添加进来,即替换掉原来的value;

使用.addHeader(String key,String value),即使当前的可以已经存在值了,只会添加新value的值,并不会移除/替换原来的值。

private final OkHttpClient client = new OkHttpClient();

  public void run() throws Exception {
    Request request = new Request.Builder()
        .url("https://api.github.com/repos/square/okhttp/issues")
        .header("User-Agent", "OkHttp Headers.java")
        .addHeader("Accept", "application/json; q=0.5")
        .addHeader("Accept", "application/vnd.github.v3+json")
        .build();

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

    System.out.println("Server: " + response.header("Server"));
    System.out.println("Date: " + response.header("Date"));
    System.out.println("Vary: " + response.headers("Vary"));
  }

2、okhttp3 Post 方法

2.1 、Post 提交键值对

很多时候,我们需要通过Post方式把键值对数据传送到服务器,okhttp3使用FormBody.Builder创建请求的参数键值对;

private void okHttp_postFromParameters() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                // 请求完整url:http://api.k780.com:88/?app=weather.future&weaid=1&&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json
                String url = "http://api.k780.com:88/";
                OkHttpClient okHttpClient = new OkHttpClient();
                String json = "{‘app‘:‘weather.future‘,‘weaid‘:‘1‘,‘appkey‘:‘10003‘," +
                        "‘sign‘:‘b59bc3ef6191eb9f747dd4e83c99f2a4‘,‘format‘:‘json‘}";
                RequestBody formBody = new FormBody.Builder().add("app", "weather.future")
                        .add("weaid", "1").add("appkey", "10003").add("sign",
                                "b59bc3ef6191eb9f747dd4e83c99f2a4").add("format", "json")
                        .build();
                Request request = new Request.Builder().url(url).post(formBody).build();
                okhttp3.Response response = okHttpClient.newCall(request).execute();
                Log.i(TAG, response.body().string());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();
}

2.2 、Post a String

可以使用Post方法发送一串字符串,但不建议发送超过1M的文本信息,如下示例展示了,发送一个markdown文本

public static final MediaType MEDIA_TYPE_MARKDOWN
      = MediaType.parse("text/x-markdown; charset=utf-8");

  private final OkHttpClient client = new OkHttpClient();

  public void run() throws Exception {
    String postBody = ""
        + "Releases\n"
        + "--------\n"
        + "\n"
        + " * _1.0_ May 6, 2013\n"
        + " * _1.1_ June 15, 2013\n"
        + " * _1.2_ August 11, 2013\n";

    Request request = new Request.Builder()
        .url("https://api.github.com/markdown/raw")
        .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))
        .build();

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

    System.out.println(response.body().string());
  }

2.3 、Post Streaming

post可以将stream对象作为请求体,依赖以Okio 将数据写成输出流形式;

public static final MediaType MEDIA_TYPE_MARKDOWN
      = MediaType.parse("text/x-markdown; charset=utf-8");

  private final OkHttpClient client = new OkHttpClient();

  public void run() throws Exception {
    RequestBody requestBody = new RequestBody() {
      @Override public MediaType contentType() {
        return MEDIA_TYPE_MARKDOWN;
      }

      @Override public void writeTo(BufferedSink sink) throws IOException {
        sink.writeUtf8("Numbers\n");
        sink.writeUtf8("-------\n");
        for (int i = 2; i <= 997; i++) {
          sink.writeUtf8(String.format(" * %s = %s\n", i, factor(i)));
        }
      }

      private String factor(int n) {
        for (int i = 2; i < n; i++) {
          int x = n / i;
          if (x * i == n) return factor(x) + " × " + i;
        }
        return Integer.toString(n);
      }
    };

    Request request = new Request.Builder()
        .url("https://api.github.com/markdown/raw")
        .post(requestBody)
        .build();

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

    System.out.println(response.body().string());
  }

2.4 、Post file

public static final MediaType MEDIA_TYPE_MARKDOWN
      = MediaType.parse("text/x-markdown; charset=utf-8");

  private final OkHttpClient client = new OkHttpClient();

  public void run() throws Exception {
    File file = new File("README.md");

    Request request = new Request.Builder()
        .url("https://api.github.com/markdown/raw")
        .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
        .build();

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

    System.out.println(response.body().string());
  }

3、其他配置

3.1 、Gson解析Response的Gson对象

如果Response对象的内容是个json字符串,可以使用Gson将字符串格式化为对象。ResponseBody.charStream()使用响应头中的Content-Type 作为Response返回数据的编码方式,默认是UTF-8

private final OkHttpClient client = new OkHttpClient();
  private final Gson gson = new Gson();

  public void run() throws Exception {
    Request request = new Request.Builder()
        .url("https://api.github.com/gists/c2a7c39532239ff261be")
        .build();
    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

    Gist gist = gson.fromJson(response.body().charStream(), Gist.class);
    for (Map.Entry<String, GistFile> entry : gist.files.entrySet()) {
      System.out.println(entry.getKey());
      System.out.println(entry.getValue().content);
    }
  }

  static class Gist {
    Map<String, GistFile> files;
  }

  static class GistFile {
    String content;
  }

3.2 、okhttp3 本地缓存

okhttp框架全局必须只有一个OkHttpClient实例(new OkHttpClient()),并在第一次创建实例的时候,配置好缓存路径和大小。只要设置的缓存,okhttp默认就会自动使用缓存功能。

package com.jackchan.test.okhttptest;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;

import com.squareup.okhttp.Cache;
import com.squareup.okhttp.CacheControl;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.File;
import java.io.IOException;

public class TestActivity extends ActionBarActivity {

    private final static String TAG = "TestActivity";

    private final OkHttpClient client = new OkHttpClient();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        File sdcache = getExternalCacheDir();
        int cacheSize = 10 * 1024 * 1024; // 10 MiB
        client.setCache(new Cache(sdcache.getAbsoluteFile(), cacheSize));
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    execute();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void execute() throws Exception {
        Request request = new Request.Builder()
                .url("http://publicobject.com/helloworld.txt")
                .build();

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

        String response1Body = response1.body().string();
        System.out.println("Response 1 response:          " + response1);
        System.out.println("Response 1 cache response:    " + response1.cacheResponse());
        System.out.println("Response 1 network response:  " + response1.networkResponse());

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

        String response2Body = response2.body().string();
        System.out.println("Response 2 response:          " + response2);
        System.out.println("Response 2 cache response:    " + response2.cacheResponse());
        System.out.println("Response 2 network response:  " + response2.networkResponse());

        System.out.println("Response 2 equals Response 1? " + response1Body.equals(response2Body));

    }
}

okhttpclient有点像Application的概念,统筹着整个okhttp的大功能,通过它设置缓存目录,我们执行上面的代码,得到的结果如下

response1 的结果在networkresponse,代表是从网络请求加载过来的,而response2的networkresponse 就为null,而cacheresponse有数据,因为我设置了缓存因此第二次请求时发现缓存里有就不再去走网络请求了。

但有时候即使在有缓存的情况下我们依然需要去后台请求最新的资源(比如资源更新了)这个时候可以使用强制走网络来要求必须请求网络数据

public void execute() throws Exception {
        Request request = new Request.Builder()
                .url("http://publicobject.com/helloworld.txt")
                .build();

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

        String response1Body = response1.body().string();
        System.out.println("Response 1 response:          " + response1);
        System.out.println("Response 1 cache response:    " + response1.cacheResponse());
        System.out.println("Response 1 network response:  " + response1.networkResponse());

        request = request.newBuilder().cacheControl(CacheControl.FORCE_NETWORK).build();
        Response response2 = client.newCall(request).execute();
        if (!response2.isSuccessful()) throw new IOException("Unexpected code " + response2);

        String response2Body = response2.body().string();
        System.out.println("Response 2 response:          " + response2);
        System.out.println("Response 2 cache response:    " + response2.cacheResponse());
        System.out.println("Response 2 network response:  " + response2.networkResponse());

        System.out.println("Response 2 equals Response 1? " + response1Body.equals(response2Body));

    }

上面的代码中

response2对应的request变成

request = request.newBuilder().cacheControl(CacheControl.FORCE_NETWORK).build();

我们看看运行结果

response2的cache response为null,network response依然有数据。

同样的我们可以使用 FORCE_CACHE 强制只要使用缓存的数据,但如果请求必须从网络获取才有数据,但又使用了FORCE_CACHE 策略就会返回504错误,代码如下,我们去okhttpclient的缓存,并设置request为FORCE_CACHE

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        File sdcache = getExternalCacheDir();
        int cacheSize = 10 * 1024 * 1024; // 10 MiB
        //client.setCache(new Cache(sdcache.getAbsoluteFile(), cacheSize));
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    execute();
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println(e.getMessage().toString());
                }
            }
        }).start();
    }

    public void execute() throws Exception {
        Request request = new Request.Builder()
                .url("http://publicobject.com/helloworld.txt")
                .build();

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

        String response1Body = response1.body().string();
        System.out.println("Response 1 response:          " + response1);
        System.out.println("Response 1 cache response:    " + response1.cacheResponse());
        System.out.println("Response 1 network response:  " + response1.networkResponse());

        request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
        Response response2 = client.newCall(request).execute();
        if (!response2.isSuccessful()) throw new IOException("Unexpected code " + response2);

        String response2Body = response2.body().string();
        System.out.println("Response 2 response:          " + response2);
        System.out.println("Response 2 cache response:    " + response2.cacheResponse());
        System.out.println("Response 2 network response:  " + response2.networkResponse());

        System.out.println("Response 2 equals Response 1? " + response1Body.equals(response2Body));

    }

3.3 、okhttp3 取消请求

如果一个okhttp3网络请求已经不再需要,可以使用Call.cancel()来终止正在准备的同步/异步请求。如果一个线程正在写一个请求或是读取返回的response,它将会接收到一个IOException

private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
  private final OkHttpClient client = new OkHttpClient();

  public void run() throws Exception {
    Request request = new Request.Builder()
        .url("http://httpbin.org/delay/2") // This URL is served with a 2 second delay.
        .build();

    final long startNanos = System.nanoTime();
    final Call call = client.newCall(request);

    // Schedule a job to cancel the call in 1 second.
    executor.schedule(new Runnable() {
      @Override public void run() {
        System.out.printf("%.2f Canceling call.%n", (System.nanoTime() - startNanos) / 1e9f);
        call.cancel();
        System.out.printf("%.2f Canceled call.%n", (System.nanoTime() - startNanos) / 1e9f);
      }
    }, 1, TimeUnit.SECONDS);

    try {
      System.out.printf("%.2f Executing call.%n", (System.nanoTime() - startNanos) / 1e9f);
      Response response = call.execute();
      System.out.printf("%.2f Call was expected to fail, but completed: %s%n",
          (System.nanoTime() - startNanos) / 1e9f, response);
    } catch (IOException e) {
      System.out.printf("%.2f Call failed as expected: %s%n",
          (System.nanoTime() - startNanos) / 1e9f, e);
    }
  }

3.4 、okhttp3 超时设置

okhttp3 支持设置连接超时,读写超时。

private final OkHttpClient client;

  public ConfigureTimeouts() throws Exception {
    client = new OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .writeTimeout(10, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .build();
  }

  public void run() throws Exception {
    Request request = new Request.Builder()
        .url("http://httpbin.org/delay/2") // This URL is served with a 2 second delay.
        .build();

    Response response = client.newCall(request).execute();
    System.out.println("Response completed: " + response);
  }

3.5 、okhttp3 复用okhttpclient配置

所有HTTP请求的代理设置,超时,缓存设置等都需要在OkHttpClient中设置。如果需要更改一个请求的配置,可以使用 OkHttpClient.newBuilder()获取一个builder对象,该builder对象与原来OkHttpClient共享相同的连接池,配置等。

如下示例,拷贝2个‘OkHttpClient的配置,然后分别设置不同的超时时间;

private final OkHttpClient client = new OkHttpClient();

  public void run() throws Exception {
    Request request = new Request.Builder()
        .url("http://httpbin.org/delay/1") // This URL is served with a 1 second delay.
        .build();

    try {
      // Copy to customize OkHttp for this request.
      OkHttpClient copy = client.newBuilder()
          .readTimeout(500, TimeUnit.MILLISECONDS)
          .build();

      Response response = copy.newCall(request).execute();
      System.out.println("Response 1 succeeded: " + response);
    } catch (IOException e) {
      System.out.println("Response 1 failed: " + e);
    }

    try {
      // Copy to customize OkHttp for this request.
      OkHttpClient copy = client.newBuilder()
          .readTimeout(3000, TimeUnit.MILLISECONDS)
          .build();

      Response response = copy.newCall(request).execute();
      System.out.println("Response 2 succeeded: " + response);
    } catch (IOException e) {
      System.out.println("Response 2 failed: " + e);
    }
  }

3.6 、okhttp3 处理验证

okhttp3 会自动重试未验证的请求。当一个请求返回401 Not Authorized时,需要提供Anthenticator

 private final OkHttpClient client;

  public Authenticate() {
    client = new OkHttpClient.Builder()
        .authenticator(new Authenticator() {
          @Override public Request authenticate(Route route, Response response) throws IOException {
            System.out.println("Authenticating for response: " + response);
            System.out.println("Challenges: " + response.challenges());
            String credential = Credentials.basic("jesse", "password1");
            return response.request().newBuilder()
                .header("Authorization", credential)
                .build();
          }
        })
        .build();
  }

  public void run() throws Exception {
    Request request = new Request.Builder()
        .url("http://publicobject.com/secrets/hellosecret.txt")
        .build();

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

    System.out.println(response.body().string());
  }

三、参考文献:

https://github.com/square/okhttp/wiki/Recipes

http://blog.csdn.net/chenzujie/article/details/46994073

http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0106/2275.html

时间: 2024-10-22 19:02:02

okhttp3使用的相关文章

Android开发之OkHttp3.4.x

android从4.4开始,HttpUrlConnection开始使用okhttp作为底层实现.实现原理如下图: 这篇博客简单说一下okhttp的使用.文字部分没有讲清楚的,可以查看代码里面的注释.首先看一下okHttp怎么工作的. 首先我们看看一个okhttp完整的网络访问,都涉及到了那几个类(这里先说核心类). 1.OkHttpClient: Call类的工厂,Call是用来发送网络请求和接收服务器响应的类.这个类实例可以设置拦截器,缓存大小,缓存目录,连接池等信息. 2.Request:是

OkHttp3 任务队列

OkHttp3 有两种运行方式: 1.同步阻塞调用并且直接返回: 2.通过内部线程池分发调度实现非阻塞的异步回调; 下面讲的是非阻塞异步回调,OkHttp在多并发网络下的分发调度过程,主要是Dispatcher对象: 多线程:多线程技术主要解决处理器单元内多个线程执行的问题,它可以显著减少处理器单元的闲置时间,增加处理器单元的吞吐能力.但如果对多线程应用不当,会增加对单个任务的处理时间 ThreadPool线程池:线程池的关键在于线程复用以减少非核心任务的损耗. 比如: T = T1+T2+T3

OkHttp3的简单使用(二)

OkHttp3的简单封装 public class OkHttpUtil { public static final String TAG="OkHttpUtil"; private static OkHttpClient client; private static OkHttpUtil httpUtil; private OkHttpUtil(){ client=new OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECO

Okhttp3上传多张图片同时传递参数

之前上传图片都是直接将图片转化为io流传给服务器,没有用框架传图片. 最近做项目,打算换个方法上传图片. Android发展到现在,Okhttp显得越来越重要,所以,这次我选择用Okhttp上传图片. Okhttp目前已经更新到Okhttp3版本了,用法跟之前相比,也有一些差别.在网上找了很多资料, 并和java后台同事反复调试,终于成功上传多张图片,同时传递一些键值对参数. 以下是我对该过程的封装: private static final MediaType MEDIA_TYPE_PNG =

Retrofit2 + OkHttp3设置Http请求头(Headers)方法汇总

在构建网络层时会遇到一个问题就是要手动配置Http请求的Headers,写入缓存Cookie,自定义的User-Agent等参数,但是对于有几十个接口的网络层,我才不想用注解配置Headers,目前网上很多文章的方法真对这两个版本都不是很适用,有的给出的方法已经被删除,有的方法会报出异常 :( 方法一: 在翻阅官方API文档整理后的方法如下: 1.  import okhttp3.Interceptor; 2.  import okhttp3.OkHttpClient; 3.  import o

[转]OkHttp3 最有营养的初级教程

一.前言 自从Android4.4开始,google已经开始将源码中的HttpURLConnection替换为OkHttp,而在Android6.0之后的SDK中google更是移除了对于HttpClient的支持,而市面上流行的Retrofit同样是使用OkHttp进行再次封装而来的.由此看见学习OkHttp的重要性. 本篇文章是以当前最新的版本 3.5.0为例(2.0及以上版本版本与3.0以上版本存在较大差异,本文不做深入讨论,请自行百度),使用Android Stuido作为开发环境,带领

Android Volley+OkHttp3+Gson 开源库的封装

博客将按照下面的步骤介绍Volley的重新封装: 1.OkHttp3的关于Volley的HttpStack实现 2.HttpRequest的实现和HttpListener回调监听的封装 3.Volley原始的Request的Wrap 4.各种方式的请求的重新实现 5.统一请求的实现 6.使用 所需依赖: compile 'com.android.volley:volley:1.0.0' compile 'com.squareup.okio:okio:1.7.0' compile 'com.squ

OkHttp3的简单使用(一)

一.导入 1)gradle方式: compile 'com.squareup.okhttp3:okhttp:3.8.0'(okhttp 最新版) compile 'com.squareup.okio:okio:1.13.0'(okio最新版) 2)jar包导入 okhttp-3.3.0.jar okio-1.8.0.jar 3)权限 <!--网络访问权限--> <uses-permission android:name="android.permission.INTERNET&

OkHttp3使用详解

引言 最初我们进行HTTP请求时使用的是HttpURLConnection或者HttpClient,那么这两者都有什么优缺点呢? HttpClient是Apache基金会的一个开源网络库,功能十分强大,API数量众多,但正是由于庞大的API数量使得我们很难在不破坏兼容性的情况下对它进行升级和扩展,所以Android团队在提升和优化HttpClient方面的工作态度并不积极.官方在Android 2.3以后就不建议用了,并且在Android 5.0以后废弃了HttpClient,在Android

Retrofit2.0通俗易懂的学习姿势,Retrofit2.0 + OkHttp3 + Gson + RxJava

Retrofit2.0通俗易懂的学习姿势,Retrofit2.0 + OkHttp3 + Gson + RxJava Retrofit,因为其简单与出色的性能,也是受到很多人的青睐,但是他和以往的通信框架还是有点区别,不过放心,因为他本身还是挺简单的,所有我相信你看完这篇文章,对基本的请求是没什么问题的,其实现在网上这样的文章也有很多了,好了,那我们直接开车吧! 一.相关资料 Github:https://github.com/square/retrofit 官网文档:http://square