package com.demo.xutils.Utils;
import android.widget.Toast;
import org.xutils.common.Callback;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.x;
/**
* Created by y on 2016/3/1.
*/
public class XutilsHttpUtils {
static RequestParams params;
static boolean error = false;
static String Myresult = null;
/**
* 带缓存的网络请求方式
*
* @param method
* @param url
* @return
*/
public static String CacheUrl(HttpMethod method, String url) {
params = new RequestParams(url);
params.setCacheMaxAge(1000 * 30);//缓存的时间,毫秒为单位
x.http().request(method, params, new Callback.CacheCallback<String>() {
@Override
public boolean onCache(String result) {
Myresult = result;
return true; // true: 信任缓存数据, 不在发起网络请求; false不信任缓存数据.
}
@Override
public void onSuccess(String result) {
//如果服务返回304或 onCache 选择了信任缓存, 这里将不会被调用
Myresult = result;
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
error = true;
Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
}
@Override
public void onCancelled(CancelledException cex) {
Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
}
@Override
public void onFinished() {
if (!error && Myresult != null) {
Toast.makeText(x.app(), "网络请求成功", Toast.LENGTH_LONG).show();
}
}
});
return Myresult;
}
/**
* 不带缓存的网络请求方式
*
* @param method
* @param url
* @return
*/
public static String NoCacheUrl(HttpMethod method, String url) {
params = new RequestParams(url);
x.http().request(method, params, new Callback.CommonCallback<String>() {
@Override
public void onSuccess(String result) {
Myresult = result;
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
error = true;
Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
}
@Override
public void onCancelled(CancelledException cex) {
Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
}
@Override
public void onFinished() {
if (!error && Myresult != null) {
Toast.makeText(x.app(), "网络请求成功", Toast.LENGTH_LONG).show();
}
}
});
return Myresult;
}
}
功能随时跟着需求走动