前言
android网络框架之OKhttp一个处理网络请求的开源项目,是安卓端最火热的轻量级框架,由移动支付Square公司贡献(该公司还贡献了Picasso)
用于替代HttpUrlConnection和Apache HttpClient(android API23 6.0里已移除HttpClient)
官网的解释如下:
基本用法
1.集成
1.1.依赖
implementation 'com.squareup.okhttp3:okhttp:3.11.0'
可以去Okhttp-Github 查看并依赖最新的版本。
1.2权限
添加网络权限
<uses-permission android:name="android.permission.INTERNET" />
2.使用
2.1 同步GET请求
- 构建OkHttpClient对象
- 构建Request对象
- 构建Call对象并通过
execute()
方法来执行同步Get请求
//同步请求
OkHttpClient okHttpClient=new OkHttpClient();
final Request request=new Request.Builder()
.url("https://www.wanandroid.com/navi/json")
.get()
.build();
final Call call = okHttpClient.newCall(request);
try {
Response response = call.execute();
Log.e("同步结果---- ",response.body().string()+"");
} catch (IOException e) {
e.printStackTrace();
}
运行后发现报错:
android.os.NetworkOnMainThreadException
在Android4.0以后,会发现,只要是写在主线程(就是Activity)中的HTTP请求,运行时都会报错,这是因为Android在4.0以后为了防止应用的ANR(Aplication Not Response)异常。解决方法就是在子线程中运行:
//同步请求
OkHttpClient okHttpClient=new OkHttpClient();
final Request request=new Request.Builder()
.url("https://www.wanandroid.com/navi/json")
.get()
.build();
final Call call = okHttpClient.newCall(request);
new Thread(new Runnable() {
@Override
public void run() {
try {
Response response = call.execute();
Log.e("同步结果---- ",response.body().string()+"");
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
2.2 异步GET请求
//异步请求
OkHttpClient okHttpClient=new OkHttpClient();
final Request request=new Request.Builder()
.url("https://www.wanandroid.com/navi/json")
.get()
.build();
final Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d("okhttp_error",e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Gson gson=new Gson();
Log.d("okhttp_success",response.body().string());
}
});
2.3 POST请求
POST请求支持提交文件,流,string,表单等等 。这里拿POST表单请求作为请求示例:
OkHttpClient okHttpClient = new OkHttpClient();
RequestBody requestBody = new FormBody.Builder()
.add("username", "qinzishuai")
.add("password", "111111")
.build();
Request request = new Request.Builder()
.url("https://www.wanandroid.com/user/login")
.post(requestBody)
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d("okhttp", "onFailure: " + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d("okhttp", "onResponse: " + response.body().string());
}
});
大家可以关注我的微信公众号:「秦子帅」一个有质量、有态度的公众号!