目录
1. 添加依赖
// Okhttp框架
implementation 'com.squareup.okhttp3:okhttp:4.9.0'
2. 简单封装
2.1 工具类
/**
* create by 星航指挥官
* create on 2020/11/26
* 不过是大梦一场空
* 课不过是孤影照惊鸿
*/
public class OkHttpUtil {
private static OkHttpClient client = null;
//创建Client对象
private static void createClient() {
if (client == null) {
client = new OkHttpClient.Builder()
.readTimeout(5, TimeUnit.SECONDS)//设置读超时
.writeTimeout(5, TimeUnit.SECONDS)设置写超时
.connectTimeout(15, TimeUnit.SECONDS)//设置连接超时
.retryOnConnectionFailure(true)//是否自动重连
.build();
}
}
/**
* 发送请求
* @param url 请求Url
* @param body 请求体,如果有请求体则发送Post请求,否则发送Get请求
* @param listener 自定义请求回调
*/
public static void Request(String url, RequestBody body, RequestListener listener) {
// 创建OkHttpClient对象
createClient();
Request request = null;
if (body != null) {
//发送Post请求
request = new Request.Builder()
.url(url)
.post(body)
.build();
} else {
//发送Get请求
request = new Request.Builder()
.url(url)
.get()
.build();
}
client.newCall(request).enqueue(new Callback() {
//Success
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
listener.onSuccess(response.body().string());
}
//Failure
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
listener.onFailed(e.getMessage());
}
});
}
//String转为requestBody
public static RequestBody stringToRequestBody(String stringBody){
//String转RequestBody String、ByteArray、ByteString都可以用toRequestBody()
MediaType mediaType=MediaType.Companion.parse("application/json;charset=utf-8");
RequestBody requestBody=RequestBody.Companion.create(stringBody,mediaType);
return requestBody;
}
//文件转为requestBody
public static RequestBody fileToRequestBody(File file){
//File转RequestBody
MediaType mediaType=MediaType.Companion.parse("text/x-markdown; charset=utf-8");
RequestBody fileBody=RequestBody.Companion.create(file,mediaType);
return fileBody;
}
}
2.2 自定义回调接口
/**
* create by 星航指挥官
* create on 2020/11/24
* 不过是大梦一场空
* 课不过是孤影照惊鸿
*/
public interface RequestListener {
/**
* 请求成功回调
*
* @param result 服务器返回的数据
*/
void onSuccess(String result);
/**
* 请求失败回调
*
* @param reason 失败原因
*/
void onFailed(String reason);
}
3. 五种常用请求方式
3.1 无参GET请求
String url = "http://106.55.xxx.xxx:8080/yourInterface";
OkHttpUtil.Request(url,null, new RequestListener() {
@Override
public void onSuccess(String data) {
Log.e(TAG, "onSuccess: "+data);
}
@Override
public void onFailed(String reason) {
Log.e(TAG, "NOT Success: "+reason);
}
});
3.2 有参GET请求
String url = "http://106.55.xxx.xxx:8080/yourInterface";
OkHttpUtil.Request(url+"?name=ALin&age=18",null, new RequestListener() {
@Override
public void onSuccess(String data) {
Log.e(TAG, "onSuccess: "+data);
}
@Override
public void onFailed(String reason) {
Log.e(TAG, "NOT Success: "+reason);
}
});
3.3 无参POST请求
String url = "http://106.55.xxx.xxx:8080/yourInterface";
//由于工具类封装的逻辑是 body!=null就发送POST请求
//所以我们new 一个RequestBody传过去 但不要添加具体参数即可
OkHttpUtil.Request(url,new FormBody.Builder().build(), new RequestListener() {
@Override
public void onSuccess(String data) {
Log.e(TAG, "onSuccess: "+data);
}
@Override
public void onFailed(String reason) {
Log.e(TAG, "NOT Success: "+reason);
}
});
3.4 有参POST请求
String url = "http://106.55.xxx.xxx:8080/yourInterface";
RequestBody body = new FormBody.Builder()
.add("name","alin")
.add("age","3")
.add("extra","阿林三岁半")
.build();
OkHttpUtil.Request(url,body, new RequestListener() {
@Override
public void onSuccess(String data) {
Log.e(TAG, "onSuccess: "+data);
}
@Override
public void onFailed(String reason) {
Log.e(TAG, "NOT Success: "+reason);
}
});
3.5 传递Json参数
String url = "http://106.55.xxx.xxx:8080/yourInterface";
JSONObject jsonParam = new JSONObject();
try {
jsonParam.put("name","ALin");
jsonParam.put("age","22");
jsonParam.put("extra","Everything is ok !");
} catch (JSONException e) {
e.printStackTrace();
}
//调用工具类中封装的方法将Json字符串转为RequestBody对象
RequestBody body = OkHttpUtil.stringToRequestBody(jsonParam.toJSONString());
OkHttpUtil.Request(url,body, new RequestListener() {
@Override
public void onSuccess(String data) {
Log.e(TAG, "onSuccess: "+data);
}
@Override
public void onFailed(String reason) {
Log.e(TAG, "NOT Success: "+reason);
}
});
}