開(kāi)始使用
在app目錄下的build.gradle中添加依賴:
implementation 'com.squareup.okhttp3:okhttp:3.13.1'
implementation 'com.squareup.okio:okio:2.2.2'
GET方法
OkHttpClient client = new OkHttpClient.Builder().build();
Request.Builder builder = new Request.Builder().url(url);
builder.method("GET", null);
Request request = builder.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
...
}
@Override
public void onResponse(Call call, Response response) throws IOException {
...
}
});
GET參數(shù)的傳遞可以使用拼接字符串的方式直接拼接到url中。
POST方法
OkHttpClient client = new OkHttpClient.Builder().build();
FormBody.Builder formBody = new FormBody.Builder();
formBody.add(key,value);
... // 添加參數(shù)
RequestBody form = formBody.build();
Request.Builder builder = new Request.Builder();
Request request = builder.post(form)
.url(url)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
...
}
@Override
public void onResponse(Call call, Response response) throws IOException {
...
}
});
封裝
由于OkHttp發(fā)送請(qǐng)求的方式比較繁瑣,需要構(gòu)建許多參數(shù)融求,所以需要我們自己進(jìn)行封裝,以下是我的封裝方式:
/**
- @author:y4ngyy
*/
public class HttpClient {
private OkHttpClient client;
private static HttpClient mClient;
private Context context;
private HttpClient(Context c) {
context = c;
client = new OkHttpClient.Builder()
.cookieJar(new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(context)))
.followRedirects(true)
.followSslRedirects(true)
.build();
}
public static HttpClient getInstance(Context c){
if (mClient == null) {
mClient = new HttpClient(c);
}
return mClient;
}
// GET方法
public void get(String url, HashMap<String,String> param, MyCallback callback) {
// 拼接請(qǐng)求參數(shù)
if (!param.isEmpty()) {
StringBuffer buffer = new StringBuffer(url);
buffer.append('?');
for (Map.Entry<String,String> entry: param.entrySet()) {
buffer.append(entry.getKey());
buffer.append('=');
buffer.append(entry.getValue());
buffer.append('&');
}
buffer.deleteCharAt(buffer.length()-1);
url = buffer.toString();
}
Request.Builder builder = new Request.Builder().url(url);
builder.method("GET", null);
Request request = builder.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
callback.failed(e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
callback.success(response);
}
});
}
public void get(String url, MyCallback callback) {
get(url, new HashMap<String, String>(), callback);
}
// POST 方法
public void post(String url, HashMap<String, String> param, MyCallback callback) {
FormBody.Builder formBody = new FormBody.Builder();
if(!param.isEmpty()) {
for (Map.Entry<String,String> entry: param.entrySet()) {
formBody.add(entry.getKey(),entry.getValue());
}
}
RequestBody form = formBody.build();
Request.Builder builder = new Request.Builder();
Request request = builder.post(form)
.url(url)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
callback.failed(e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
callback.success(response);
}
});
}
public interface MyCallback {
void success(Response res) throws IOException;
void failed(IOException e);
}
}
想法有以下幾點(diǎn):
- 在
get()
和post()
方法中猖毫,將需要的參數(shù)以HashMap傳遞鍵值對(duì)保礼,并把相應(yīng)操作封裝。 - 第二個(gè)
get()
重載是考慮到不需要參數(shù)的GET請(qǐng)求的情況甩挫。 - 留下
myCallback
接口來(lái)對(duì)不同請(qǐng)求做處理贴硫。 - 由于需要保持cookie來(lái)做登錄等操作,所以用到了第三方庫(kù)PersistentCookieJar
- 考慮到cookie的問(wèn)題伊者,在不同的activity間需要使用同一個(gè)實(shí)例才行英遭,有想過(guò)使用Intent序列化傳遞對(duì)象,但由于activity太多亦渗,傳遞太繁瑣挖诸,所以直接寫成單例模式。
對(duì)于OkHttp的源碼還沒(méi)有深究法精,有時(shí)間再繼續(xù)研究多律。
具體使用方法
- 調(diào)用
HttpClient.getInstance()
獲取實(shí)例 - 使用實(shí)例調(diào)用get和post方法,其中需要傳入url搂蜓,參數(shù)(get可以不傳)以及MyCallBack回調(diào)
只是菜雞一個(gè)..有錯(cuò)還請(qǐng)指正..繼續(xù)努力學(xué)習(xí)