前言
第一次用okhttp的时候的版本号是2.x,当时看到github上也是2.x的版本,但现在重新去用okhttp的时候,发现有很多都不一样了,这里记录一下okhttp的一些用法,以及遇到困难时的解决办法
如果你还想使用okhttp2.x的话,就请百度自行查看,这里有个传送门Android网络编程(五)OkHttp2.x用法全解析
1.okhttp3的基本用法
1. 基本的配置
compile 'com.squareup.okhttp3:okhttp:+'
注意,这里使用的是最新版本的okhttp,我们就是要追赶人家的开发步伐
如果你想就用一个的话,下面是
compile 'com.squareup.okhttp3:okhttp:3.4.1'
添加权限:
<uses-permission android:name="android.permission.INTERNET"/>
//下面这些事使用到缓存的时候需要用的
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
2.普通的get和post的方法
//普通的异步的get请求
Request request = new Request.Builder()
.url("http://apis.baidu.com/heweather/weather/free?city=beijing")
.method("GET", null)//这行可省略
.header("apikey", CONSTS.apikey)
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Toast.makeText(getApplicationContext(), "请求失败", Toast.LENGTH_SHORT).show();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//这里咱们先不讲缓存,到后面再讲
str = response.toString()+"\n"+response.headers()+"\n"+response.body().string();
Log.i("response", str + "");
//回调不是在主线程,所以更新ui需要到主线程
runOnUiThread(new Runnable() {
@Override
public void run() {
text.setText(str+"");
}
});
}
});
普通的post表单请求
//异步post
public void POST(View view) {
//添加表单内容
RequestBody formBody = new FormBody.Builder()
.add("city", "beijing")
.build();
//多项内容,这个是传多种参数的的
RequestBody multiformBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("title", "Square Logo")
.addFormDataPart("image", "logo-square.png",
RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
.build();
Request request = new Request.Builder()
.url("http://apis.baidu.com/heweather/weather/free")
.header("apikey", CONSTS.apikey)
.post(formBody)
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
str = response.toString()+"\n"+response.headers()+"\n"+response.body().string();
Log.i("response", str + "");
runOnUiThread(new Runnable() {
@Override
public void run() {
text.setText(str+"");
}
});
}
});
}
在这里请注意,get请求和2.x的内容变化不是很大,post内容的时候添加属性值的时候参数变了,OkHttp3异步POST请求和OkHttp2.x有一些差别就是没有FormEncodingBuilder这个类,替代它的是功能更加强大的FormBody和MultipartBody,这两个的类的用法都是builder,和Request的用法相似
3. 上传文件
。。。
4.下载文件
。。。