封装get、post请求:
~~~
public class HttpKit {
private static final String BASE_URL = CanYouUrl.API_DOMAIN;
private static AsyncHttpClient client = new AsyncHttpClient();
private static final PersistentCookieStore cookieStore = new PersistentCookieStore(
App.mContext);
public static void cancelAll() {
client.cancelAllRequests(true);
}
public static void directGet(String url, RequestParams params,
AsyncHttpResponseHandler responseHandler) {
client.get(url, params, responseHandler);
}
/**
* get请求
*
* @param url 路径
* @param params 参数
* @param responseHandler 回调
*/
public static void get(String url, RequestParams params,
AsyncHttpResponseHandler responseHandler) {
client.addHeader("Content-Type", "application/json");
client.get(getAbsoluteUrl(url), params, responseHandler);
}
/**
* post请求
*
* @param url 路径
* @param params 参数
* @param responseHandler 回调
*/
public static void post(String url, RequestParams params,
AsyncHttpResponseHandler responseHandler) {
client.addHeader("Content-Type", "application/json");
client.put(getAbsoluteUrl(url), params, responseHandler);
}
/**
* post 请求
*
* @param context 上下文
* @param url 路径
* @param json 实体json
* @param responseHandler 回调
*/
public static void post(Context context, String url, String json,
AsyncHttpResponseHandler responseHandler) {
client.addHeader("Content-Type", "application/json");
try {
ByteArrayEntity entity = new ByteArrayEntity(json.getBytes("UTF-8"));
client.post(context, getAbsoluteUrl(url),
entity, "application/json", responseHandler);
} catch (Exception e) {
CanYouLog.e("网络请求错误:" + e.toString());
}
}
/**
* api地址
*
* @param relativeUrl
* @return
*/
private static String getAbsoluteUrl(String relativeUrl) {
client.setCookieStore(cookieStore);
return BASE_URL + relativeUrl;
}
public static void clearCookie() {
cookieStore.clear();
}
}
~~~
使用实例:
~~~
/**
* 用户登录
*
* @param username 用户名
* @param password 密码
* @param responseHandler 回调
*/
public static void login(String username, String password,
AsyncHttpResponseHandler responseHandler) {
RequestParams params = new RequestParams();
params.put("username", username);
params.put("password", password);
HttpKit.get(CanYouUrl.login, params, responseHandler);
}
~~~