博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
okhttp3使用
阅读量:6279 次
发布时间:2019-06-22

本文共 18037 字,大约阅读时间需要 60 分钟。

hot3.png

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

compile 'com.squareup.okhttp3:okhttp:3.3.1' 1 二、基本使用

1、okhttp3 Get 方法

1.1 、okhttp3 同步 Get方法

/**

  • 同步Get方法 */ private void okHttp_synchronousGet() { new Thread(new Runnable() { @Override public void run() { try { String url = ""; 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(); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 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. 1 2 3 获取返回的数据,可通过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 1 2 3 4 5 6 当然也可以获取流输出形式;

public final java.io.InputStream byteStream() 1 1.2 、okhttp3 异步 Get方法

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

/**

  • 异步 Get方法 */ private void okHttp_asynchronousGet(){ try { Log.i(TAG,"main thread id is "+Thread.currentThread().getId()); String url = ""; 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(); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 注: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("") .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"));

} 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 2、okhttp3 Post 方法

2.1 、Post 提交键值对

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

private void okHttp_postFromParameters() { new Thread(new Runnable() { @Override public void run() { try { // 请求完整url: String url = ""; 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(); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 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());

} 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 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());

} 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 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());

} 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 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("") .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
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; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 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();@Overrideprotected 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));}

} 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 okhttpclient有点像Application的概念,统筹着整个okhttp的大功能,通过它设置缓存目录,我们执行上面的代码,得到的结果如下

这里写图片描述

response1 的结果在networkresponse,代表是从网络请求加载过来的,而response2的networkresponse 就为null,而cacheresponse有数据,因为我设置了缓存因此第二次请求时发现缓存里有就不再去走网络请求了。 但有时候即使在有缓存的情况下我们依然需要去后台请求最新的资源(比如资源更新了)这个时候可以使用强制走网络来要求必须请求网络数据

public void execute() throws Exception { Request request = new Request.Builder() .url("") .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));}

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 上面的代码中 response2对应的request变成

request = request.newBuilder().cacheControl(CacheControl.FORCE_NETWORK).build(); 1 我们看看运行结果

这里写图片描述

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));}

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 这里写图片描述

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("") // 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);}

} 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 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("") // This URL is served with a 2 second delay. .build();

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

} 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 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("") // 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);}

} 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 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("") .build();

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

} 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 三、参考文献:

转载于:https://my.oschina.net/u/1177694/blog/699771

你可能感兴趣的文章
使用shell脚本自动监控后台进程,并能自动重启
查看>>
Flex&Bison手册
查看>>
MySQL 5.6 for Windows 解压缩版配置安装
查看>>
solrCloud+tomcat+zookeeper集群配置
查看>>
/etc/fstab,/etc/mtab,和 /proc/mounts
查看>>
Apache kafka 简介
查看>>
socket通信Demo
查看>>
技术人员的焦虑
查看>>
js 判断整数
查看>>
建设网站应该考虑哪些因素
查看>>
mongodb $exists
查看>>
js实现页面跳转的几种方式
查看>>
sbt笔记一 hello-sbt
查看>>
常用链接
查看>>
pitfall override private method
查看>>
!important 和 * ----hack
查看>>
聊天界面图文混排
查看>>
控件的拖动
查看>>
svn eclipse unable to load default svn client的解决办法
查看>>
Android.mk 文件语法详解
查看>>