上次写了xListView+OKHttp的xListView篇,主要是说了它的heard和foot的添加,现在这里说的是网络请求部分,主要以在android studio开发为主。
(一):导入OKHttp包
在android studio里面直接引入即可:
compile 'com.squareup.okhttp:okhttp:2.4.0'
在eclipse中需要导入okhttp-2.4.0.jar包或者其他版本
(二):封装网络请求公用类
首先新建类DataRequest和接口DataRequestListener,DataRequestListener包含responseSuccess和responseFail两个相应回调的方法。
public interface DataRequestListener { void responseSuccess(int status,String result, String cacheUrl); void responseFail(int status, String result); }
因为在http请求的时候我们要注意url,参数,请求方式,请求回调和执行五个方面,所以,我们分别定义四个方法分别处理
1:url方法
public DataRequest setUrl(String url){ this.url=url; return this; }2:添加参数方法
public DataRequest setParameters(Map<String, String> params) { this.mParams = params; return this; }3:定义请求参数
public DataRequest setMethod(String method) { this.mMethod = method; return this; }
其中我们将传递来的string类型的method复制给我们在DataRequest类中定义的全局变量mMethod,这样我们在执行的时候做判断
请求回调的时候我们上面已经定义了一个DataRequestListener接口,里面有针对网络请求返回的成功和失败做了判断,因此我们这边需要定义一个handler来处理我们的接口中的回调方法,如下:
private DataRequestListener mLister;
private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch(msg.what) { case HANDLER_RESPSONSE: int status = msg.arg1; String result = (String) msg.obj; if (status == 200) { mLister.responseSuccess(status, result, null); } else { mLister.responseFail(status, result); } break; default: break; } } };
可知,我们对接口中的成功和失败的方法进行了封装,这样我们在调用的时候让相关的activity实现DataRequestListener,并重写其中的方法即可
private void dataResponse(Response response, final Handler mhandler, final String cacheUrl) { status = response.code(); mReponseInfo = null; if (status == 200) { try { mReponseInfo = response.body().string(); } catch (Exception e) { e.printStackTrace(); } } else if (status == 404) { mReponseInfo = "访问路径出错"; } else if (status == 500) { mReponseInfo = "服务器出错"; } else { mReponseInfo = "网络失败"; } mHandler.post(new Runnable() { @Override public void run() { if (status == 200) { mLister.responseSuccess(status, mReponseInfo, cacheUrl); } else { mLister.responseFail(status, mReponseInfo); } } }); }
5:执行网络请求
直接执行excute,但是在这里我们需要做对post还是ge t做一下判断
public void excute() {
try {
if (mMethod.equalsIgnoreCase("get")) {
//执行get
get();
} else if (mMethod.equalsIgnoreCase("post")) {
//执行post
post();
}
} catch (Exception e) {
e.printStackTrace();
}
}
里面对不同的请求方式定义了不同的方法
post:
public void post() {
if (null != mLister) {
String cacheUrl = "";
//网络不可用时
if (mContext != null && !NetworkUtil.isNetworkAvailable(mContext)) {
//看看缓存里面有没有数据
String cacheInfo = CacheManager.getCacheInfo(mContext, cacheUrl);
if (TextUtils.isEmpty(cacheInfo)) {
mLister.responseFail(0, cacheInfo);
} else {
mLister.responseSuccess(200, cacheInfo, cacheUrl);
}
return;
}
if (mThreadPool.isShutdown()) {
mThreadPool = Executors.newFixedThreadPool(THREAD_COUNT);
}
mThreadPool.execute(new Runnable() {
@Override
public void run() {
try {
Request request = new Request.Builder().url(url).post(addParams(mParams))
.build();
Response response = client.newCall(request).execute();
dataResponse(response, mHandler, null);
} catch (final Exception ej) {
ej.printStackTrace();
mHandler.post(new Runnable() {
public void run() {
mLister.responseFail(0, ej.getMessage());
}
});
}
}
});
}
}
get请求:
public void get() {
if (null != mLister) {
//判断线程池有没有关掉
if (mThreadPool.isShutdown()) {
mThreadPool = Executors.newFixedThreadPool(THREAD_COUNT);
}
mThreadPool.execute(new Runnable() {
@Override
public void run() {
try {
Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();
dataResponse(response, mHandler, null);
} catch (final Exception e) {
e.printStackTrace();
mHandler.post(new Runnable() {
public void run() {
mLister.responseFail(0, e.getMessage());
}
});
}
}
});
}
}
最后还有一个addParams方法用于组合一下,在get请求中可以不需要改方法
public RequestBody addParams(Map<String, String> mParams){
FormEncodingBuilder formEncodingBuilder = new FormEncodingBuilder();
RequestBody.create(MediaType.parse("application/json; charset=utf-8"),"json");
if (null != mParams && mParams.size() > 0) {
List<String> keyList = new ArrayList<String>();
for(String key : mParams.keySet()){
String value = mParams.get(key);
formEncodingBuilder.add(key, value);
}
}
RequestBody formBody = formEncodingBuilder.build();
return formBody;
}
最后不能忘了DataRequest的构造函数和调用方法
public static DataRequest create(Context context) { return new DataRequest(context); }
public DataRequest(Context context) { mContext = context; }
具体调用这个封装的类,我们这么用呢?煎蛋。。。。
(三)调用
肯定要implements接口DataRequestListener,并实现方法
哪里需要就在哪里写一个request方法,比如:
private void request() { final String deviceInfoUrl = “http://wwww.baidu.com”; // 详情 DataRequest.create(getApplicationContext()) .setUrl(deviceInfoUrl) .setMethod("post") .setParameters(params) .setCallback(this) .excute(); }即可。。。。。。。。。
附上资源: