okhttp二次封装 瞎写哈哈哈
打算换个网络框架,网上搜索了一圈发现okHttp还是不错的,不过网络请求实际上不是一个 异步的,不明白为什么有回调了却不做成异步的方式,所以自己对okhttp进行了个二次封装,能用就行。
先屡屡思路,先要有一个父类来处理网络请求,父类实现一个网络请求接口,并重写抽象方法,然后子类继承父类,调用父类重写的抽象发放然后发送请求,还需要做一个回调,把请求来的数据发送到activity,然后要实现异步就要在父类的回调里用一下handler,在大致就是这么个套路。
先在android studio中 添加okhttp的依赖
compile 'com.squareup.okhttp:okhttp:2.6.0'
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.squareup.okhttp:okhttp:2.6.0'
compile 'de.greenrobot:greendao:1.3.7'
testCompile 'junit:junit:4.12'
compile 'com.google.code.gson:gson:2.2.4'
}
然后写个回调需要用的接口,一个成功的回调和一个失败的回调
public interface OkHttpCallBack {
void onFailure(Request request, String e);
void onResponse(JSONObject response) throws IOException;
}
然后自己在定义一个接口,里面分别是get请求和post请求的抽象方法。接口里好像都是抽象方法哈哈哈
public interface OkHttpInterface {
/**
* 发送 http get 请求
*
* @param url
* @param params
* @param httpRequestListener
*/
void sendHttpGet(Activity activity, String url, Map<String, String> params, final OkHttpCallBack okHttpCallBack);
/**
* 发送 http post 请求
*
* @param url
* @param params
* @param bodyParams
* @param httpRequestListener
*/
void sendHttPost(Activity activity, String url, Map<String, String> params, Map<String, String> bodyParams, OkHttpCallBack okHttpCallBack);
}
然後就可以写父类了,实现请求的接口,重写get和post方法
在对应的方法里 调用 okhttp的get和post方法就好了,最后会有一个 回调,我们只需要在这个回调里用一下handler.post来实现异步就可以了,最后我们用自己的写的回调接口把数据传到activity就可以了。
public class OkHttpService implements OkHttpInterface {
private OkHttpClient okHttpClient = new OkHttpClient();
private Handler handler = new Handler();
@Override
public void sendHttpGet(final Activity activity, String url, Map<String, String> params, final OkHttpCallBack okHttpCallBack) {
okHttpClient = new OkHttpClient();
Request.Builder builder = new Request.Builder();
final Request request = builder.get().url(url).build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(final Request request, final IOException e) {
}
@Override
public void onResponse(final Response response) throws IOException {
sendSuccessResultCallback(response, okHttpCallBack);
}
});
}
@Override
public void sendHttPost(Activity activity, String url, Map<String, String> params, Map<String, String> bodyParams, final OkHttpCallBack httpRequestListener) {
FormEncodingBuilder formEncodingBuilder = new FormEncodingBuilder();
Set entries = params.entrySet();
if (entries != null) {
Iterator iterator = entries.iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry) iterator.next();
Object key = entry.getKey();
Object value = entry.getValue();
formEncodingBuilder.add(key.toString(), value.toString());
}
RequestBody body = formEncodingBuilder.build();
Request request = new Request.Builder().url(url).post(body).build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
sendFailedStringCallback(request, e.getMessage(), httpRequestListener);
}
@Override
public void onResponse(Response response) throws IOException {
sendSuccessResultCallback(response, httpRequestListener);
}
});
}
}
private void sendSuccessResultCallback(final Response response, final OkHttpCallBack okHttpInterface) throws IOException {
final String str = response.body().string();
handler.post(new Runnable() {
@Override
public void run() {
try {
okHttpInterface.onResponse(new JSONObject(str));
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
private void sendFailedStringCallback(final Request response, final String e, final OkHttpCallBack okHttpInterface) {
handler.post(new Runnable() {
@Override
public void run() {
okHttpInterface.onFailure(response, e);
}
});
}
}
接下来就可以写我们的子类了,子类需要做的工作很简单 继承父类 然后写需要的请求方法,并且把参数传到父类里面执行
public class HomeService extends OkHttpService {
public void get(Activity activity, String url, String str, final OkHttpCallBack callback) {
sendHttpGet(activity, url, null, new OkHttpCallBack() {
@Override
public void onFailure(Request request, String e) {
callback.onFailure(request, e);
}
@Override
public void onResponse(JSONObject response) throws IOException {
callback.onResponse(response);
}
});
}
public void login(final Activity activity, String username, String password, final OkHttpCallBack callback) {
String paramsStr = HTTPURLConfig.HEARD_URL + HTTPURLConfig.LOGIN;
Map<String, String> paramsMap = new HashMap<>();
paramsMap.put("client_id", HTTPURLConfig.CLIENT_ID);
paramsMap.put("client_secret", HTTPURLConfig.CLIENT_SECRET);
paramsMap.put("grant_type", HTTPURLConfig.GRANT_TYPE);
paramsMap.put("username", username);
paramsMap.put("password", password);
sendHttPost(activity, paramsStr, paramsMap, null, new OkHttpCallBack() {
@Override
public void onFailure(Request request, String e) {
callback.onFailure(request, e);
}
@Override
public void onResponse(JSONObject response) throws IOException {
saveToken(activity, response);
callback.onResponse(response);
}
});
}
private void saveToken(Activity activity, JSONObject response) {
try {
AccessTokenVO AccessTokenVO = new AccessTokenVO(null, response.getString("access_token"));
DBManager.getInstance(activity).insert(AccessTokenVO);
RefreshTokenVO refreshTokenVO = new RefreshTokenVO(null, response.getString("refreshTokenVO"));
DBManager.getInstance(activity).insert(refreshTokenVO);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
然后我们的activity就可以创建 子类的对象 然后调用 请求方法 传入参数 ,就得到接口返回的数据了
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.login_btn:
HomeService homeService = new HomeService();
homeService.login(LoginActivity.this, userName.getText().toString(), password.getText().toString(), new OkHttpCallBack() {
@Override
public void onFailure(Request request, String e) {
Toast.makeText(LoginActivity.this, "失败 ", Toast.LENGTH_SHORT).show();
}
@Override
public void onResponse(JSONObject response) throws IOException {
startActivity(new Intent(LoginActivity.this, HomeActivity.class));
}
});
break;
}
}
自己尝试着封装的,最后接口是通了,不知道自己上面说的对不对,有错的地方欢迎指出。