1、okhttp3简介:
一个处理网络请求的开源项目,是安卓端最火热的轻量级框架
2、okhttp3配置
1.Android Studio 配置gradle:
implementation 'com.squareup.okhttp3:okhttp:3.12.0'
2,添加网络权限:
<uses-permission android:name="android.permission.INTERNET"/>
03、okhttp3使用思路
get请求思路
1.获取okHttpClient对象
2.构建Request对象
3.构建Call对象
4.通过Call.enqueue(callback)方法来提交异步请求;execute()方法实现同步请求
post请求思路
1.获取okHttpClient对象
2.创建RequestBody
3.构建Request对象
4.构建Call对象
5.通过Call.enqueue(callback)方法来提交异步请求;execute()方法实现同步请求
04、OkHttp3 发送异步请求(GET)
String url = "http://";
//第一步获取okHttpClient对象
OkHttpClient client = new OkHttpClient();
//第二步构建Request对象
Request request = new Request.Builder()
.url(url)
.get()
.build();
//第三步构建Call对象
Call call = client.newCall(request);
//第四步:异步get请求
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("onFailure", e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String result = response.body().string();
Log.i("result", result);
}
});
05、OkHttp3 发送异步请求(POST)
//接口参数 String username,String password
String url = "http://";
//第一步创建OKHttpClient
OkHttpClient client = new OkHttpClient.Builder()
.build();
//第二步创建RequestBody(Form表达)
RequestBody body = new FormBody.Builder()
.add("username", "admin")
.add("password", "123456")
.build();
//第三步创建Rquest
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
//第四步创建call回调对象
final Call call = client.newCall(request);
//第五步发起请求
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("onFailure", e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String result = response.body().string();
Log.i("result", result);
}
});