Android OkHttp的使用
前提:
添加联网权限
<uses-permission android:name="android.permission.INTERNET" />
添加依赖
implementation "com.squareup.okhttp3:okhttp:4.9.0"
GET请求:
例:请求如下接口:
(1)地址:http://49.232.114.172:8080/yunying/qufumanage/getList.json
(2)请求方式:get
(3)请求参数:无
(4)返回结果:
{
"code":200,
"msg":"success",
"list":["赵钱孙李","周吴郑王","冯陈褚卫","蒋沈韩杨","朱秦尤许","何吕施张"]
}
第一步:创建OkHttpClient对象
String path = "http://49.232.114.172:8080/yunying/qufumanage/getList.json";
OkHttpClient okHttpClient = new OkHttpClient();
第二步:构造Request对象 需要添加请求的方式和请求地址
Request request =new Request.Builder().get().url(path).build();
第三步:将Request封装为Call
Call call = client.newCall(request);
第四步:发送请求
异步请求:
call.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call,@NotNull IOException e) {
//返回失败
Log.d("TAG","onFailure: " + e.getMessage());
}
@Override
public void onResponse(@NotNull Call call,@NotNull Response response)throws IOException {
Log.d("TAG","response.code(): " + response.code());
//返回成功
if (response.code() ==200) {
String string = response.body().string();
}
}
});
}
同步请求:(不建议使用)
Response response = call.execute();
if (response.code() ==200) {
String string = response.body().string();
Log.d("TAG","string=" + string);
}
POST请求:
例:请求如下接口:
(1) 地址:http://49.232.114.172:8080/yunying/qufumanage/login.php
(2)请求方式:post
(3)请求参数:”username”: “root” “password”:”root123456” (FormUrlEncoded表单形式)
(4)返回结果:
{
"code":200,
"message":"success",
}
第一步:创建OkHttpClient对象
OkHttpClient okHttpClient =new OkHttpClient();
第二步:创建FormBody参数 add(key,value)
FormBody formBody =new FormBody.Builder()
.add("username","root")
.add("password","root123456")
.build();
第三步:构造Request对象 需要添加请求的方式和请求地址
String path ="http://49.232.114.172:8080/yunying/qufumanage/login.php";
Request request =new Request.Builder().post(formBody).url(path).build();
第四步:将Request封装为Call
Call call = okHttpClient.newCall(request);
第五步:发送异步请求(不建议使用同步请求,所以就没有写)
call.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call,@NotNull IOException e) {
//请求失败
}
@Override
public void onResponse(@NotNull Call call,@NotNull Response response)throws IOException {
//请求成功
if(response.code() ==200){
//获取数据
String string = response.body().string();
}
}
});