当前位置: 移动技术网 > IT编程>移动开发>Android > Android使用OKHttp包处理HTTP相关操作的基本用法讲解

Android使用OKHttp包处理HTTP相关操作的基本用法讲解

2019年07月24日  | 移动技术网IT编程  | 我要评论

天竺山森林公园好玩吗,山水藏龙bbs,路灯节电

okhttp是一款高效的http客户端,支持连接同一地址的链接共享同一个socket,通过连接池来减小响应延迟,还有透明的gzip压缩,请求缓存等优势。(github页:https://github.com/square/okhttp)

android为我们提供了两种http交互的方式:httpurlconnection 和 apache http client,虽然两者都支持https,流的上传和下载,配置超时,ipv6和连接池,已足够满足我们各种http请求的需求。但更高效的使用http 可以让您的应用运行更快、更节省流量。而okhttp库就是为此而生。
okhttp是一个高效的http库:

  • 支持 spdy ,共享同一个socket来处理同一个服务器的所有请求
  • 如果spdy不可用,则通过连接池来减少请求延时
  • 无缝的支持gzip来减少数据流量
  • 缓存响应数据来减少重复的网络请求
  • 会从很多常用的连接问题中自动恢复。

如果您的服务器配置了多个ip地址,当第一个ip连接失败的时候,okhttp会自动尝试下一个ip。okhttp还处理了代理服务器问题和ssl握手失败问题。
使用 okhttp 无需重写您程序中的网络代码。okhttp实现了几乎和java.net.httpurlconnection一样的api。如果您用了 apache httpclient,则okhttp也提供了一个对应的okhttp-apache 模块。


引入
可以通过下载jar包直接导入工程地址
或者通过构建的方式导入
maven:

<dependency>
 <groupid>com.squareup.okhttp</groupid>
 <artifactid>okhttp</artifactid>
 <version>2.4.0</version>
</dependency>

gradle:

compile 'com.squareup.okhttp:okhttp:2.4.0'

用法
在向网络发起请求的时候,我们最常用的就是get和post,下面就来看看如何使用
1. get
在okhttp,每次网络请求就是一个request,我们在request里填写我们需要的url,header等其他参数,再通过request构造出call,call内部去请求参数,得到回复,并将结果告诉调用者。
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.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);
    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 response = client.newcall(request).execute();
    if(response.issuccessful()){
      system.out.println(response.code());
      system.out.println(response.body().string());
    }
  }
}
我们通过request.builder传入url,然后直接execute执行得到response,通过response可以得到code,message等信息。
这个是通过同步的方式去操作网络请求,而android本身是不允许在ui线程做网络请求操作的,因此我们需要自己开启一个线程。
当然,okhttp也支持异步线程并且有回调返回,有了上面同步的基础,异步只要稍加改动即可
private void enqueue(){
    request request = new request.builder()
        .url("http://publicobject.com/helloworld.txt")
        .build();
    client.newcall(request).enqueue(new callback() {
      @override
      public void onfailure(request request, ioexception e) {
      }
      @override
      public void onresponse(response response) throws ioexception {
        //not ui thread
        if(response.issuccessful()){
          system.out.println(response.code());
          system.out.println(response.body().string());
        }
      }
    });
  }
就是在同步的基础上讲execute改成enqueue,并且传入回调接口,但接口回调回来的代码是在非ui线程的,因此如果有更新ui的操作记得用handler或者其他方式。
2、post
说完get该介绍些如何使用post,post情况下我们一般需要传入参数,甚至一些header,传入参数或者header
比如传入header
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(); 
传入post参数
requestbody formbody = new formencodingbuilder()
  .add("platform", "android")
  .add("name", "bug")
  .add("subject", "xxxxxxxxxxxxxxx")
  .build();
  request request = new request.builder()
   .url(url)
   .post(body)
   .build();
可以看出来,传入header或者post参数都是传到request里面,因此最后的调用方式也和get方式一样
response response = client.newcall(request).execute();
  if (response.issuccessful()) {
    return response.body().string();
  } else {
    throw new ioexception("unexpected code " + response);
  }
这个代码是同步网络请求,异步就改成enqueue就行了。

请求缓存
在网络请求中,缓存技术是一项应用比较广泛的技术,需要对请求过的网络资源进行缓存,而okhttp也支持这一技术,也使用十分方便,前文涨经常出现的okhttpclient这个时候就要派送用场了。看下面代码
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的大功能,通过它设置缓存目录,我们执行上面的代码,得到的结果如下
201671395230108.jpg (848×127)
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();
我们看看运行结果
201671395608033.jpg (853×142)
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));
  }
201671395741595.jpg (882×84)
取消操作
网络操作中,经常会使用到对请求的cancel操作,okhttp的也提供了这方面的接口,call的cancel操作。使用call.cancel()可以立即停止掉一个正在执行的call。如果一个线程正在写请求或者读响应,将会引发ioexception,同时可以通过request.builder.tag(object tag)给请求设置一个标签,并使用okhttpclient.cancel(object tag)来取消所有带有这个tag的call。但如果该请求已经在做读写操作的时候,cancel是无法成功的,会抛出ioexception异常。
public void canceltest() 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("call is cancel:" + call.iscanceled() + "%n");
      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);
    }
  }
成功取消
2016713100051268.jpg (613×103)
取消失败
2016713100130237.jpg (867×102)

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网