android okhttp3的封裝
阿新 • • 發佈:2019-02-07
最近由於苦逼的學校課程,我們需要用android開發一款教學輔助軟體,所以我就開始看android開發的相關知識,今天實戰的時候發現okhttp還是蠻好用的,但是我不會對其進行封裝,於是乎就百度了一發,看了下別人的部落格,發現有位大佬寫的真的好用,就把複製過來,以備以後使用。
大佬部落格連結在此:
下面是程式碼:
public class HttpUtil {
private static OkHttpClient client = null;
private HttpUtil() {}
public static OkHttpClient getInstance () {
if (client == null) {
synchronized (HttpUtil.class) {
if (client == null)
client = new OkHttpClient();
}
}
return client;
}
/**
* Get請求
*
* @param url
* @param callback
*/
public static void doGet(String url, Callback callback) {
Request request = new Request.Builder()
.url(url)
.build();
Call call = getInstance().newCall(request);
call.enqueue(callback);
}
/**
* Post請求傳送鍵值對資料
*
* @param url
* @param mapParams
* @param callback
*/
public static void doPost(String url, Map<String, String> mapParams, Callback callback) {
FormBody.Builder builder = new FormBody.Builder();
for (String key : mapParams.keySet()) {
builder.add(key, mapParams.get(key));
}
Request request = new Request.Builder()
.url(url)
.post(builder.build())
.build();
Call call = getInstance().newCall(request);
call.enqueue(callback);
}
/**
* Post請求傳送JSON資料
*
* @param url
* @param jsonParams
* @param callback
*/
public static void doPost(String url, String jsonParams, Callback callback) {
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8")
, jsonParams);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Call call = getInstance().newCall(request);
call.enqueue(callback);
}
}