封装的OkHttpUtils

  工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class OkHttpUtils {
private static OkHttpUtils okHttpUtils;//封装的OkHtpp工具类
private static Request.Builder builder;
private static OkHttpClient okHttpClient;

public static OkHttpUtils getInstance(){
builder = new Request.Builder();
if (okHttpUtils == null){
okHttpUtils = new OkHttpUtils();
okHttpClient = new OkHttpClient();
}
return okHttpUtils;
}

/**
* 添加请求地址
* @param url 请求地址
*/
public OkHttpUtils url(String url){
builder.url(url);
return okHttpUtils;
}

/**
* 添加请求头
* @param name 请求头键名
* @param value 请求头键值
*/
public OkHttpUtils addHeader(String name, String value){
builder.addHeader(name, value);
return okHttpUtils;
}

/**
* post请求
* @param requestBody 请求体
* @param callback 回调
*/
public void post(RequestBody requestBody, Callback callback){
Request request = OkHttpUtils.builder.post(requestBody).build();
okHttpClient.newCall(request).enqueue(callback);
}

/**
* get请求
* @param callback 回调
*/
public void get(Callback callback){
Request request = OkHttpUtils.builder.get().build();
okHttpClient.newCall(request).enqueue(callback);
}

// 禁止创建对象调用
private OkHttpUtils() {}
}

  发送post请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
RequestBody requestBody = RequestBody.create(content, MediaType.parse("text/x-markdown; charset=utf-8"));
OkHttpUtils.getInstance().url(url).post(requestBody, new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
Log.d(TAG, "请求失败 = " + e);
}

@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
ResponseBody body = response.body();
if (response.isSuccessful() && body != null){
String string = body.string();
Log.d(TAG, "result = " + string);
}
else {
Log.d(TAG, "请求失败");
}
}
});

  发送get请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
OkHttpUtils.getInstance().url(url).get(newCallback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
Log.d(TAG, "加载失败 = " + e);
}

@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
ResponseBody body = response.body();
if (response.isSuccessful() && body != null){
String result = body.string();
Log.d(TAG, "result = " + result);
}
else {
Log.d(TAG, "加载失败");
}
}
});