您的位置:首页 > 理论基础 > 计算机网络

Android HttpUtil工具类

2015-11-16 00:00 519 查看
摘要: 指定类型解析,android-async-http + gson 自定义类型解析指定对象

/**
*  get 方式 请求  返回指定类型
* @param mContext
* @param url 路径
* @param requestMap 参数值,转json 传输
* @param callback 结果回调
*/
public void get(final Context mContext, String url, RequestMapBean requestMap, final ResultCallback callback) {
RequestParams param = RequestEncryDecryptUtil.commonJsonRequestParams(mContext, requestMap);
AsyncHttpUtil.get(mContext, url, param, new BaseJsonHttpResponseParse(mContext) {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
if (callback.mType == String.class) {
callback.onSuccess(response);
} else {
Object o = mGson.fromJson(string, callback.mType);
callback.onSuccess(o);
}
}

@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
callback.onError(errorResponse);
}
});
}


public  abstract class ResultCallback<T>
{
Type mType;

public ResultCallback()
{
mType = getSuperclassTypeParameter(getClass());
}

static Type getSuperclassTypeParameter(Class<?> subclass)
{
Type superclass = subclass.getGenericSuperclass();
if (superclass instanceof Class)
{
throw new RuntimeException("Missing type parameter.");
}
ParameterizedType parameterized = (ParameterizedType) superclass;
return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);
}

public abstract void onSuccess(T response);

public abstract void onError(JSONObject errorResponse);
}


public class AsyncHttpUtil {

private static final String TAG = "AsyncHttpUtil";

private static AsyncHttpClient client = new AsyncHttpClient();

public static void get(Context context, String url, RequestParams param, AsyncHttpResponseHandler handler) {
if (PhoneUtil.isConnectNet(context)) {;
client.get(context, getAbsoluteUrl(url), param, handler);
} else {
ToastUtil.showMsg(context, "网络已断开");
handler.sendFinishMessage();
handler.onCancel();
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  指定类型解析