这里主要讲述OkHttp3的基本用法,原则上可以直接复制粘贴使用。
1.引入OkHttp
我们可以直接在Modules下点击搜索需要的框架,如图:
但是最近AS的搜索功能实在有点不给力,不举啊,=经常会搜索不到我们需要的内容,所以建议直接在gradle文件中添加引用:
implementation 'com.squareup.okhttp3:okhttp:3.2.0'
然后网络同步下载一下即可。
2.get和post请求
OkHttp的网络请求分为同步和异步请求,直接上代码:
//同步网络请求下的get请求
new Thread(new Runnable() {
@Override
public void run() {
//同步请求下的get请求
OkHttpClient client1 = new OkHttpClient();
Request request1 = new Request.Builder().url(url)
.addHeader("name", "lisi").addHeader("age", "12").build();
Call call1 = client1.newCall(request1);
try {
Response response1 = call1.execute();
if(response1.isSuccessful()){
Log.e("同步网络请求下的get请求", response1.body().string());
Log.e("主线程不能执行网络请求,所以开启了子线程", "线程ID是:" + Thread.currentThread());
}else{
Log.e("同步网络请求下的get请求","请求失败了呢");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
//同步网络请求下的post请求
new Thread(new Runnable() {
@Override
public void run() {
OkHttpClient client2 = new OkHttpClient();
Request request2 = new Request.Builder().url(url).build();
RequestBody body2 = new FormBody.Builder().add("name", "zhangsan")
.add("age", "13").build();
Call call2=client2.newCall(request2);
try {
Response response2=call2.execute();
if(response2.isSuccessful()){
Log.e("同步网络请求下的post请求",response2.body().string());
Log.e("主线程中不能进行网络操作,所以开启了子线程","当前线程ID:"+Thread.currentThread());
}else{
Log.e("同步网络请求的post请求","请求失败了呢");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
//异步网络线程下的get请求
OkHttpClient client3=new OkHttpClient();
Request request3=new Request.Builder().url(url)
.addHeader("name","wangwu").addHeader("age","15").build();
Call call3=client3.newCall(request3);
call3.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e("异步网络请求","网络请求失败了呢");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.e("异步网络请求下的get请求",response.body().string());
Log.e("异步网络请求","当前线程ID是:"+Thread.currentThread());
}
});
//异步网络请求下的post请求
OkHttpClient client4=new OkHttpClient();
Request request4=new Request.Builder().url(url).build();
RequestBody body4=new FormBody.Builder().add("name","sunliu").add("age","12").build();
Call call4=client4.newCall(request4);
call4.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e("异步网络请求下的post请求","网络请求失败了呢");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.e("异步网络请求下的post请求",response.body().string());
Log.e("异步网络请求的线程ID","线程ID是:"+Thread.currentThread());
}
});
以上基本实现了OkHttp的四种基本网络请求方式。