OkHttp3框架的使用
1.导入okhttp的jar包
切换到project下,将okhttp-3.2.0.jar和okio-1.12.0放到app/libs下,为项目导入该jar包,右键jar包Add As Library选择需要导入的项目即可成功导入。
或在需要导入的项目下的build.gradle加入如下代码(dependencies类):
implementation files('D:/android_studio/cunfang/MyApplication/app/libs/okhttp-3.2.0.jar')
implementation files('D:/android_studio/cunfang/MyApplication/app/libs/okio-1.12.0.jar')
这里的路径是你jar包的路径
2.发起网络请求
Get请求方式:
public void OkHttpGet()
{
new Thread(){
@Override
public void run() {
//获取一个OkHttpClient对象
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("这里是接口地址").build();
try {
Response response = client.newCall(request).execute();
if(response.isSuccessful())
{
//如果请求成功,通知Handler更新数据
result="请求结果:"+response.body().string();
handler.sendEmptyMessage(0x100);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
在子线程中进行耗时操作后,使用Handler发送消息通知UI线程更新
Post请求方式:
public void OkhttpPost(){
new Thread(){
@Override
public void run() {
OkHttpClient client = new OkHttpClient();
//创建一个表单对象
FormBody.Builder formBody = new FormBody.Builder();
formBody.add("UserName","张三");
formBody.add("PassWord","123456");
Request request = new Request.Builder().url("这里是接口地址")
.post(formBody.build())
.build();
try {
Response response = client.newCall(request).execute();
if(response.isSuccessful())
{
result="User结果:"+response.body().string();
handler.sendEmptyMessage(0x100);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
okhttp3默认请求方式是Get,Post请求方式需要声明
返回的response中,response.code()为请求码,成功默认返回200。
response.message()为返回结果,成功默认返回OK。
response.body()为返回内容