【Android】OkHttp3总结与封装
开始使用
在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参数的传递可以使用拼接字符串的方式直接拼接到url中。
POST方法
OkHttpClient client = new OkHttpClient.Builder().build();
FormBody.Builder formBody = new FormBody.Builder();
formBody.add(key,value);
... // 添加参数
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发送请求的方式比较繁琐,需要构建许多参数,所以需要我们自己进行封装,以下是我的封装方式:
/**
- @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) {
// 拼接请求参数
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);
}
}
想法有以下几点:
- 在
get()
和post()
方法中,将需要的参数以HashMap传递键值对,并把相应操作封装。 - 第二个
get()
重载是考虑到不需要参数的GET请求的情况。 - 留下
myCallback
接口来对不同请求做处理。 - 由于需要保持cookie来做登录等操作,所以用到了第三方库PersistentCookieJar
- 考虑到cookie的问题,在不同的activity间需要使用同一个实例才行,有想过使用Intent序列化传递对象,但由于activity太多,传递太繁琐,所以直接写成单例模式。
对于OkHttp的源码还没有深究,有时间再继续研究。
只是菜鸡一个..有错还请指正..继续努力学习