**版权声明:本文为小斑马伟原创文章,转载请注明出处!
自Android6.0之后就废除了HttpClient,同时官方承认了OKHttp请求框架。我们市面上比较流行的框架包括Vollery OKHttp Retrofit,而Vollery就是基于HttpClient技术实现的,当HttpClient被废除之后,导致Vollery失去大量使用效果。所以OKHttp成为市面上最大的网络请求框架。接下我们我们来介绍下这个网络框架 以及该框架如何使用。
一、OKHttp简介
- 1.一个处理网络请求的开源项目
- 2.由移动支付公司Square贡献
- 3.用于替代HttpUrlConnection和Apache HttpClient
- 4.OkHttp支持Android 2.3及其以上版本,JDK1.7以上
二、OKHttp特点
- 1.支持HTTP2/SPDY
- 2.socket自动选择最好路线,并支持自动重连
- 3.拥有自动维护的socket连接池,减少握手次数
- 4.拥有队列线程池,轻松写并发
- 5.拥有Interceptors轻松处理请求和响应(比如透明GZIP压缩,LOGGING)
- 6.基于Headers的缓存策略
三、OKHttp引入
Android Studio 配置 gradle:
compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.squareup.okio:okio:1.7.0'
添加网络请求权限:
四、OKHttp同步和异步
OKHttp同步请求execute 方法 :网络请求和发起请求是在同一个线程里面。
String url = "http://www.baidu.com/";
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder() //表示一个发起网络请求 对网络请求做了一个封装 可以声明请求的地址和带了一些请求参数和同步信息
.url(url)
.build();
Call call = okHttpClient .newCall(request); 通过newCall方法得到 Call对象。 Call对象里面的execute() 表示发起一个同步请求,同时返回的结果是Response对象 (服务器反应的结果)
try{
Response response = call.execute();
System.out.println(response.body().string());
} catch (IOException e) {
e.prinStackTrace();
}
可以在request的的header添加参数。例如Cookie ,User-Agent等:
Request request = new Request.Builder()
.url(url)
.header("键","值")
.header("键","值")
.builder();
OKHttp异步请求enqueue()方法:网络请求和发起请求不是在同一个线程里面。
String url = "http://www.baidu.com/";
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Call call = okHttpClient .newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call,IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
System.out.prinln(我是异步线程,线程ID为:"+Thread.currentThread().getId());
}
});
五、OKHttp(POST请求)
POST请求:基本上是客户端上传数据到服务器中去。POST请求创建request和GET请求是一样的,POST请求需要提交一个表单--RequestBody。RequestBody需要指定Content-Type,常见的数据格式有三种:
- 1.application/x-www-form-urlencoded 数据是个普通表单
- 2.multipart/form-data 数据里有文件
- 3.application/json 数据是个json
POST请求-上传键值对(普通表单)
FormBody继承自RequestBody 指定数据类型为.application/x-www-form-urlencoded
六、发送POST请求,上传键值对
private List setCookieList;
/**
* send post request key-value
*
*/
private void okHttpPostPairs() {
String url = "http://35.185.149.288/user/do-login";
FormBody.Builder formBody = new FormBody.Builder(); //创建表单请求体
formBody.add("login_username","weiwei"); //传递键值对参数
formBody.add("login_password","000000"); //传递键值对参数
RequestBody body = formBody.build() ;
final Request request = new Request.Builder().url(url).post(body).build();
Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
setCookieList = request.headers("Set-Cookie");
Log.i(TAG,"repose result :"+response.body().string());
}
});
}
七、下载文件
private void okHttpDownload() {
final File file = new File(Environment.getExternalStorageDirectory().toString()+"/default.png");
String url = "http://35.185.149.288/staic/user/image/default.jsp";
Request request = new Request.Builder().url(url).build();
Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.i(TAG,"repose result :" + response.body().toString());
InputStream is = null;
byte[] buf = new byte[2048];
int len = 0 ;
FileOutputStream fos = null;
long total = response.body().contentLength();
Log.i(TAG,"repose total length :" + total);
long current = 0 ;
is = response.body().byteStream();
fos = new FileOutputStream(file);
while((len = is.read(buf))!=-1) {
current +=len;
fos.write(buf,0,len);
}
fos.close();;
Log.i(TAG,"download icon success");
}
});
}
八、上传JSON数据
/**
* post request upload josnString
*/
private void okHttpPostJson() {
String url = "http://35.185.149.288/user/do-login";
RequestBody body = RequestBody.create(MediaType.parse("aaplication/json;charset=utf-8"),"这里是你的json字符串");
final Request request = new Request.Builder().url(url).post(body).build();
Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
setCookieList = request.headers("Set-Cookie");
Log.i(TAG,"repose result :"+response.body().string());
}
});
}
九、上传文件
/**
* post upLoad people image
*/
private void okHttpUpLoad() {
String url = "http://35.185.149.288/file/upload-img";
File file = new File(Environment.getExternalStorageDirectory()+"/ic_launcher.png");
//不带参数的RequestBody
// RequestBody body = RequestBody.create(MediaType.parse("image/png"),file);
//带参数的RequestBody
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.addFormDataPart("filename","testpng");
builder.addFormDataPart("file",file.getName(),RequestBody.create(MediaType.parse("image/png"),file));
RequestBody body = builder.build();
final Request request = new Request.Builder().url(url).post(body)
.header("Cookie",setCookieList.get(0)).header("Cookie",setCookieList.get(1)).build();
Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.i(TAG,"upload success repose result :"+response.body().string());
}
});
}
十、GET请求
/**
* send get request
* get message
*
*/
private void okHttpGet() {
String url = "http://35.185.149.288//user/get-big-direction";
Request request = new Request.Builder().url(url).build();
Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.i(TAG,"repose result :" + response.body().string());
}
});
}