欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android中okhttp3使用详解

程序员文章站 2023-12-18 22:34:10
一、引入包 在项目module下的build.gradle添加okhttp3依赖 compile 'com.squareup.okhttp3:okhttp:3....

一、引入包

在项目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的大功能,通过它设置缓存目录,我们执行上面的代码,得到的结果如下

Android中okhttp3使用详解

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

我们看看运行结果

Android中okhttp3使用详解

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

  }

Android中okhttp3使用详解

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:

下一篇: