当前位置: 移动技术网 > 移动技术>移动开发>Android > Android App开发中HTTP扩展包OkHttp的入门使用指南

Android App开发中HTTP扩展包OkHttp的入门使用指南

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

android 开发,不可避免的会用到网络技术,而多数情况下,我们都是使用 http 协议来发送和接收网络数据。android 系统主要提供两种方式来进行 http 通信,httpurlconnection 和 httpclient,但是从 android 2.3 及以后版本中,google 推荐使用 httpurlconnection,究其原因,就是由于 httpclient 的 api 数量过多,使得我们很难在不破坏兼容性的情况下对它进行升级和扩展,所以目前 android 团队在提升和优化 httpclient 方面的工作态度并不积极。httpurlconnection 是一种多用途、轻量极的 http 客户端,使用它来进行 http 操作可以适用于大多数的应用程序。虽然 httpurlconnection 的 api 提供的比较简单,但是同时这也使得我们可以更加容易地去使用和扩展它。

但也正是因为这样,httpurlconnection 的使用还是比较复杂的,如果不进行适当封装的话,很容易就会写出不少重复代码,于是乎,一些android 网络通信框架也就应运而生,今天要讲的就是 okhttp 开源框架。

okhttp 可以做很多事,包括上传字符串、上传文件、上传流、上传表格参数、上传多部分的请求、响应 json、响应缓存等。目前主要流行 json 数据通信,所以我们就来讲讲基于 json 通信的 get 和 post 请求与响应。

环境准备

介绍了这么多理论知识,接下来就进入实战阶段了,首先下载 okhttp 的 jar 包,可以去 github 下载最近的包。

这是最新下载地址:https://search.maven.org/remote_content?g=com.squareup.okhttp3&a=okhttp&v=latest
当然,你也可以在项目中直接添加编译(用于 android studio):compile 'com.squareup.okhttp3:okhttp:3.2.0'
okhttp 的项目地址:https://github.com/square/okhttp

除此之外,还需要添加一个 okhttp 的依赖包:okio.jar,下载地址:https://search.maven.org/remote_content?g=com.squareup.okio&a=okio&v=latest
项目地址:https://github.com/square/okio
编译地址:compile 'com.squareup.okio:okio:1.6.0'

例子

1.请求一个url

这里例子请求一个url,并以字符串的格式打印内容,主要代码:

okhttpclient client = new okhttpclient();

string run(string url) throws ioexception {
 request request = new request.builder()
   .url(url)
   .build();

 response response = client.newcall(request).execute();
 return response.body().string();
}

2.向服务器post请求

向服务器发送post请求,主要代码:

public static final mediatype json
  = mediatype.parse("application/json; charset=utf-8");
 
okhttpclient client = new okhttpclient();
 
string post(string url, string json) throws ioexception {
 requestbody body = requestbody.create(json, json);
 request request = new request.builder()
   .url(url)
   .post(body)
   .build();
 response response = client.newcall(request).execute();
 return response.body().string();
}

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

相关文章:

验证码:
移动技术网