OkHttp Wiki翻译(四)使用说明

来源:互联网 发布:淘宝卫浴好店 编辑:程序博客网 时间:2024/06/04 23:22

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

下面是翻译: 


说明

我们写了一些说明,用于演示如何解决OkHttp的常见问题。 (你应该)阅读他们,以了解整个过程是如何协同工作的。 自由剪切并粘贴这些例子; 这就是他们的目的。

同步Get

下载一个文件,打印其响应头,并以字符串的形式打印其响应正文。

响应体上的string()方法对于小文档来说既方便又高效。但是如果响应体很大(大于1 MiB),则应该避免使用string()方法,因为它会将整个文档都加载到内存中。在这种情况下,更应该以流的方式来处理响应体。

private final OkHttpClientclient = new OkHttpClient();

 

public void run() throwsException

{

    Request request = new Request.Builder()

   .url("http://publicobject.com/helloworld.txt")

    .build();

 

    Response response =client.newCall(request).execute();

    if (!response.isSuccessful()) throw newIOException("Unexpected code " + response);

 

    Headers responseHeaders =response.headers();

    for (int i = 0; i <responseHeaders.size(); i++)

    {

       System.out.println(responseHeaders.name(i) + ": " +responseHeaders.value(i));

    }

 

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

}

 

异步Get

在工作线程上下载文件,并在响应可读时调用。在响应头准备就绪后进行回调。 阅读响应体还可能会导致阻塞。 OkHttp当前还不提供部分接收响应主体的异步API。

private final OkHttpClientclient = new OkHttpClient();

 

public void run() throwsException

{

    Request request = new Request.Builder()

   .url("http://publicobject.com/helloworld.txt")

    .build();

 

    client.newCall(request).enqueue(newCallback()

    {

        @Override public void onFailure(Callcall, IOException e)

        {

            e.printStackTrace();

        }

 

        @Override public void onResponse(Callcall, Response response) throws IOException

        {

            if (!response.isSuccessful()) thrownew IOException("Unexpected code " + response);

 

            Headers responseHeaders =response.headers();

            for (int i = 0, size =responseHeaders.size(); i < size; i++)

            {

               System.out.println(responseHeaders.name(i) + ": " +responseHeaders.value(i));

            }

 

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

        }

    });

}

 

 访问响应头

通常情况下,HTTP header的工作方式类似于Map <String,String>:每个字段都有一个值或为空。但是有些header允许多个值,如Guava的Multimap。 例如,HTTP响应提供多个Vary header是合法和通用的。 OkHttp的API尝试使这两种情况的使用都很舒适。

当在写请求头时,应使用 “请求头(名称,值)”来设置值的唯一的名称。如果已经存在现有的值,则应该在添加新值之前将它们删除。使用 addHeader(name,value)来添加请求头,这种方式不会删除已经存在的请求头。

当读取响应头时,使用header(name)返回最后一次出现的命名值。 通常这也是唯一的出现! 如果没有值,header(name)将会返回null。 要读取所有字段的值来作为一个列表,请使用 headers(name)。

要访问所有的header,请使用支持通过索引访问的Headers类。

private final OkHttpClientclient = new OkHttpClient();

 

public void run() throwsException

{

    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 newIOException("Unexpected code " + response);

 

    System.out.println("Server: " +response.header("Server"));

    System.out.println("Date: " +response.header("Date"));

    System.out.println("Vary: " +response.headers("Vary"));

}

 

 

提交字符串

使用HTTP POST将请求体发送到服务。此示例将一个markdown文档post到以HTML格式呈现为markdown的Web服务。因为整个请求体同时在内存中,所以避免使用这个API发布大的(大于1个MiB)文档。

public static final MediaTypeMEDIA_TYPE_MARKDOWN

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

 

private final OkHttpClientclient = new OkHttpClient();

 

public void run() throwsException

{

    String postBody = ""

                      + "Releases\n"

                      + "--------\n"

                      + "\n"

                      + " * _1.0_ May 6,2013\n"

                      + " * _1.1_ June 15,2013\n"

                      + " * _1.2_ August11, 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 newIOException("Unexpected code " + response);

 

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

}

 

 提交数据流

这里我们以流的方式发送一个请求体。请求体的内容会在流写入的同时生成。此示例中的流会直接进入Okio缓冲接收器。您的程序可能更适合使用OutputStream,您可以从BufferedSink.outputStream()获取。

public static final MediaTypeMEDIA_TYPE_MARKDOWN

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

 

private final OkHttpClientclient = new OkHttpClient();

 

public void run() throwsException

{

    RequestBody requestBody = new RequestBody()

    {

        @Override public MediaTypecontentType()

        {

            return MEDIA_TYPE_MARKDOWN;

        }

 

        @Override public voidwriteTo(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) returnfactor(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 newIOException("Unexpected code " + response);

 

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

}

 

 

提交文件

将文件用作请求体很容易。

public static final MediaTypeMEDIA_TYPE_MARKDOWN

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

 

private final OkHttpClientclient = new OkHttpClient();

 

public void run() throwsException

{

    File file = newFile("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 newIOException("Unexpected code " + response);

 

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

}

 

从表单参数发送Post请求

使用FormBody.Builder构建一个像HTML <form>标签一样的请求体。名称和值将会以HTML兼容的表单URL编码形式进行编码。

private final OkHttpClientclient = new OkHttpClient();

 

public void run() throwsException

{

    RequestBody formBody = newFormBody.Builder()

    .add("search", "JurassicPark")

    .build();

    Request request = new Request.Builder()

   .url("https://en.wikipedia.org/w/index.php")

    .post(formBody)

    .build();

 

    Response response = client.newCall(request).execute();

    if (!response.isSuccessful()) throw newIOException("Unexpected code " + response);

 

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

}

 

 

提交多个请求

MultipartBody.Builder可以构建与HTML文件上传表单兼容的复杂请求体。 多部分请求体的每个部分本身就是一个请求体,并且这个请求体可以定义自己的请求头。如果已经存在,这些头部信息应该描述请求体,例如其内容位置(Content-Disposition)。 如果内容长度和内容类型可用,那么这些都会自动添加。

private static final StringIMGUR_CLIENT_ID = "...";

private static finalMediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

 

private final OkHttpClientclient = new OkHttpClient();

 

public void run() throwsException

{

    // Use the imgur image upload API asdocumented at https://api.imgur.com/endpoints/image

    RequestBody requestBody = newMultipartBody.Builder()

    .setType(MultipartBody.FORM)

    .addFormDataPart("title","Square Logo")

    .addFormDataPart("image","logo-square.png",

                    RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))

    .build();

 

    Request request = new Request.Builder()

    .header("Authorization","Client-ID " + IMGUR_CLIENT_ID)

   .url("https://api.imgur.com/3/image")

    .post(requestBody)

    .build();

 

    Response response =client.newCall(request).execute();

    if (!response.isSuccessful()) throw newIOException("Unexpected code " + response);

 

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

}

 

用Gson解析JSON数据

Gson是用于在JSON和Java对象之间进行转换的方便的API。 这里我们使用它来对来自GitHub返回的JSON进行进行解析。

 

请注意,ResponseBody.charStream()使用Content-Type响应头来选择在解析响应体时要使用的字符集。 如果未指定字符集,则默认为UTF-8。

private final OkHttpClientclient = new OkHttpClient();

private final Gson gson = newGson();

 

public void run() throwsException

{

    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;

}

 

 响应缓存

要缓存响应,您需要一个可以读取和写入的缓存目录,并对缓存的大小进行限制。 缓存目录应该是私有的,不受信任的应用程序不能读取其内容!

 

让多个缓存同时访问同一个缓存目录是一个错误。大多数应用程序应该调用新的OkHttpClient()一次,配置它们的缓存,并在任何地方使用相同的实例。 否则两个缓存实例将彼此冲突,损坏响应缓存,并可能会导致程序崩溃。

 

响应缓存使用HTTP头进行所有配置。 您可以添加类似于这样的缓存控制的请求头:max-stale = 3600,OkHttp的缓存将会使其符合要求。 您的网络服务器可以配置缓存响应的时间长短与其自己的响应头,如Cache-Control:max-age = 9600。缓存和头部信息会在网络请求响应时强制去返回,后者强制网络以get的形式去返回可用的响应。

private final OkHttpClientclient;

 

public CacheResponse(FilecacheDirectory) throws Exception

{

    int cacheSize = 10 * 1024 * 1024; // 10 MiB

    Cache cache = new Cache(cacheDirectory,cacheSize);

 

    client = new OkHttpClient.Builder()

    .cache(cache)

    .build();

}

 

public void run() throwsException

{

    Request request = new Request.Builder()

   .url("http://publicobject.com/helloworld.txt")

    .build();

 

    Response response1 =client.newCall(request).execute();

    if (!response1.isSuccessful()) throw newIOException("Unexpected code " + response1);

 

    String response1Body =response1.body().string();

    System.out.println("Response 1response:          " + response1);

    System.out.println("Response 1 cacheresponse:    " +response1.cacheResponse());

    System.out.println("Response 1 networkresponse:  " +response1.networkResponse());

 

    Response response2 =client.newCall(request).execute();

    if (!response2.isSuccessful()) throw newIOException("Unexpected code " + response2);

 

    String response2Body = response2.body().string();

    System.out.println("Response 2response:          " + response2);

    System.out.println("Response 2 cacheresponse:    " +response2.cacheResponse());

    System.out.println("Response 2 networkresponse:  " +response2.networkResponse());

 

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

}

 

要防止响应使用缓存,请使用CacheControl.FORCE_NETWORK。要防止它使用网络,请使用CacheControl.FORCE_CACHE。 警告:如果您使用FORCE_CACHE并且响应需要网络,OkHttp将返回504请求失败的响应。

 

取消请求

使用Call.cancel()可以立即停止正在进行的请求。如果线程当前正在写请求或读取响应数据,它将收到一个IOException。 当不再需要请求时,应使用它来节省网络资源;例如,当您的用户在使用应用程序结束导航时。同步和异步呼叫都可以取消。

private finalScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

private final OkHttpClientclient = new OkHttpClient();

 

public void run() throwsException

{

    Request request = new Request.Builder()

   .url("http://httpbin.org/delay/2") // This URL is served witha 2 second delay.

    .build();

 

    finallong startNanos = System.nanoTime();

    final Call call = client.newCall(request);

 

    // Schedule a job to cancel the call in 1second.

    executor.schedule(new Runnable()

    {

        @Override public void run()

        {

            System.out.printf("%.2fCanceling call.%n", (System.nanoTime() - startNanos) / 1e9f);

            call.cancel();

            System.out.printf("%.2fCanceled call.%n", (System.nanoTime() - startNanos) / 1e9f);

        }

    }, 1, TimeUnit.SECONDS);

 

    try

    {

        System.out.printf("%.2f Executingcall.%n", (System.nanoTime() - startNanos) / 1e9f);

        Response response = call.execute();

        System.out.printf("%.2f Call wasexpected to fail, but completed: %s%n",

                          (System.nanoTime() -startNanos) / 1e9f, response);

    }

    catch (IOException e)

    {

        System.out.printf("%.2f Callfailed as expected: %s%n",

                          (System.nanoTime() -startNanos) / 1e9f, e);

    }

}

 

超时

当访问不可到达时,就会发生超时。 网络中断可能是由于客户端连接问题,服务器可用性问题或这两者之间。 OkHttp支持连接,读取和写入的超时动作。

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() throwsException

{

    Request request = new Request.Builder()

   .url("http://httpbin.org/delay/2") // This URL is served witha 2 second delay.

    .build();

 

    Response response =client.newCall(request).execute();

    System.out.println("Responsecompleted: " + response);

}

 

 

每一请求的配置

所有HTTP客户端配置都建立在OkHttpClient的基础上,包括代理的设置,超时和高速缓存。 当您需要更改单个调用的配置时,请调用OkHttpClient.newBuilder()方法。 这将返回与原始客户端共享相同连接池,调度程序和配置的构建器。 在下面的示例中,我们发出一个超时500 ms的请求,另一个请求超时3000 ms。

private final OkHttpClientclient = new OkHttpClient();

 

public void run() throwsException

{

    Request request = new Request.Builder()

   .url("http://httpbin.org/delay/1") // This URL is served witha 1 second delay.

    .build();

 

    try

    {

        // Copy to customize OkHttp for thisrequest.

        OkHttpClient copy = client.newBuilder()

                            .readTimeout(500,TimeUnit.MILLISECONDS)

                            .build();

 

        Response response =copy.newCall(request).execute();

        System.out.println("Response 1succeeded: " + response);

    }

    catch (IOException e)

    {

        System.out.println("Response 1failed: " + 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 2succeeded: " + response);

    }

    catch (IOException e)

    {

        System.out.println("Response 2failed: " + e);

    }

}

 

处理认证(证书)

OkHttp可以自动重试未经身份验证的请求。 当答复为401未授权时,将要求验证者提供凭证。实现应该构建一个新的请求,其中应包含缺少的凭据。 如果没有可用的凭据,返回null以跳过重试。

 

使用Response.challenges()方法来获取约束和任何证书认证。当通过基本认证之后,请使用Credentials.basic(用户名,密码)对请求请求头进行编码。

  private final OkHttpClient client;

 

public Authenticate()

{

    client = new OkHttpClient.Builder()

    .authenticator(new Authenticator()

    {

        @Override public Requestauthenticate(Route route, Response response) throws IOException

        {

            System.out.println("Authenticatingfor response: " + response);

           System.out.println("Challenges: " + response.challenges());

            String credential =Credentials.basic("jesse", "password1");

            returnresponse.request().newBuilder()

                   .header("Authorization",credential)

                   .build();

        }

    })

    .build();

}

 

public void run() throwsException

{

    Request request = new Request.Builder()

   .url("http://publicobject.com/secrets/hellosecret.txt")

    .build();

 

    Response response =client.newCall(request).execute();

    if (!response.isSuccessful()) throw newIOException("Unexpected code " + response);

 

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

}

为了避免在身份验证失效时的多次重试,您可以返回null来放弃。例如,您可能希望在尝试过这些证书认证之后放弃时跳过重试。

if(credential.equals(response.request().header("Authorization")))

{

    return null; // If we already failed withthese credentials, don't retry.

}

当您遇到应用定义的尝试限制时,您也可以跳过重试:

if (responseCount(response)>= 3)

{

    return null; // If we've failed 3 times,give up.

}

 

上面的代码依赖于这个响应Count()方法:

private intresponseCount(Response response)

{

    int result = 1;

    while ((response =response.priorResponse()) != null)

    {

        result++;

    }

    return result;

}

  

原创粉丝点击