当前位置: 移动技术网 > 移动技术>移动开发>Android > Android第三方HTTP网络支持包OkHttp的基础使用教程

Android第三方HTTP网络支持包OkHttp的基础使用教程

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

okhttp 包的设计和实现的首要目标是高效。这也是选择 okhttp 的重要理由之一。okhttp 提供了对最新的 http 协议版本 http/2 和 spdy 的支持,这使得对同一个主机发出的所有请求都可以共享相同的套接字连接。如果 http/2 和 spdy 不可用,okhttp 会使用连接池来复用连接以提高效率。okhttp 提供了对 gzip 的默认支持来降低传输内容的大小。okhttp 也提供了对 http 响应的缓存机制,可以避免不必要的网络请求。当网络出现问题时,okhttp 会自动重试一个主机的多个 ip 地址。
(okhttp的github主页:https://github.com/square/okhttp)
http 客户端所要执行的任务很简单,接受 http 请求并返回响应。每个 http 请求包括 url,http 方法(如 get 或 post),http 头和请求的主体内容等。http 请求的响应则包含状态代码(如 200 或 500),http 头和响应的主体内容等。虽然请求和响应的交互模式很简单,但在实现中仍然有很多细节要考虑。okhttp 会对收到的请求进行一定的处理,比如增加额外的 http 头。同样的,okhttp 也可能在返回响应之前对响应做一些处理。例如,okhttp 可以启用 gzip 支持。在发送实际的请求时,okhttp 会加上 http 头 accept-encoding。在接收到服务器的响应之后,okhttp 会先做解压缩处理,再把结果返回。如果 http 响应的状态代码是重定向相关的,okhttp 会自动重定向到指定的 url 来进一步处理。okhttp 也会处理用户认证相关的响应。

如何使用
1.gradle

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

2.initial
建议只要new一个实体做全部的操作就行了

okhttpclient = new okhttpclient();
okhttpclient.setconnecttimeout(30, timeunit.seconds);
okhttpclient.setreadtimeout(30, timeunit.seconds);

3.get
okhttp 使用调用(call)来对发送 http 请求和获取响应的过程进行抽象。下面代码中给出了使用 okhttp 发送 http 请求的基本示例。首先创建一个 okhttpclient 类的对象,该对象是使用 okhttp 的入口。接着要创建的是表示 http 请求的 request 对象。通过 request.builder 这个构建帮助类可以快速的创建出 request 对象。这里指定了 request 的 url 为 http://www.baidu.com。接着通过 okhttpclient 的 newcall 方法来从 request 对象中创建一个 call 对象,再调用 execute 方法来执行该调用,所得到的结果是表示 http 响应的 response 对象。通过 response 对象中的不同方法可以访问响应的不同内容。如 headers 方法来获取 http 头,body 方法来获取到表示响应主体内容的 responsebody 对象。
okhttp 最基本的 http 请求

public class syncget {
  public static void main(string[] args) throws ioexception {
  okhttpclient client = new okhttpclient();

  request request = new request.builder()
      .url("http://www.baidu.com")
      .build();

  response response = client.newcall(request).execute();
  if (!response.issuccessful()) {
    throw new ioexception("服务器端错误: " + 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());
  }
}

4.post
有了上面get的基础,我们直接顺便来看post:

builde requestbody
requestbody formbody = new formencodingbuilder()
  .add("name", "cuber")
  .add("age", "26")
  .build();

request request = new request.builder()
   .url(url)
   .post(requestbody)
   .build();

5.send
把上面build出来的request带进来

response response = client.newcall(request).execute();//如果response回传是null, 就代表timeout或没有网络

或是你想使用callback...
response response = client.newcall(request).enqueue(new callback() {

  @override
  public void onfailure(request request, ioexception e) {
    //timeout或 没有网络 
    //注意!这里是backgroundthread
  }

  @override
    public void onresponse(response response) throws ioexception {
    //成功
    //注意!这里是backgroundthread
  }
});

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网