赞
踩
最近项目中网络请求使用的AsyncHttpClient,这里简单总结下使用方法,既加强记忆,有能和大家分享下。
implementation 'com.loopj.android:android-async-http:1.4.9'
- //创建实例
- AsyncHttpClient client=new AsyncHttpClient();
- //
- client.get(this, "", new TextHttpResponseHandler() {
- @Override
- public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
-
- }
-
- @Override
- public void onSuccess(int statusCode, Header[] headers, String responseString) {
-
- }
- });
直接调用十分简单,如上述代码。
直接调用看似十分简单,但当接口数量增大时,整个代码会十分繁琐,因为每个类都要重复创建实例,调用方法。所以封装起来很有必要,首先我们封装一个httpClient类,
- public class HttpClient {
- private static final String TAG = "HttpClient";
- //contentType
- private static final String CONTENT_TYPE_FORM = "application/x-www-form-urlencoded";
-
- //创建实例
- private static final AsyncHttpClient ASYNC_CLIENT = new AsyncHttpClient();
-
- //可在此处配置header,例如机型,版本号,umengType等
- static {
- ASYNC_CLIENT.setTimeout(20000);
- }
-
-
- //get方法
- //ResponseHandler 是TextHttpResponseHandler的子类,下面会有介绍
- public static RequestHandle doGet(String relativeUrl, RequestParams params, ResponseHandler responseHandler){
-
- params=addCommonParams(params);
- //完整url
- String url=getAbsolutUrl(relativeUrl);
- //在此处添加网络监测
- if (NetUtils.hasNetwork(App.getInstance())){
- return ASYNC_CLIENT.get(null,url,getCommonHeader(),params,responseHandler);
- }else{
- Log.v(TAG, ">> 网络连接异常");
- onNetDisabled(responseHandler);
- return null;
- }
-
- }
-
-
- public static RequestHandle doPost(String relativeUrl, RequestParams params, ResponseHandler responseHandler){
- params=addCommonParams(params);
- String url=getAbsolutUrl(relativeUrl);
- if (NetUtils.hasNetwork(App.getInstance())){
- return ASYNC_CLIENT.post(null,url,getCommonHeader(),params,CONTENT_TYPE_FORM,responseHandler);
- }else{
- Log.v(TAG, ">> 网络连接异常");
- onNetDisabled(responseHandler);
- return null;
- }
-
- }
-
-
- //阿里云全国物流快递查询(单号识别)
- public static Header[] getCommonHeader(){
- Header[] headers = new BasicHeader[1];
- headers[0]=new BasicHeader("Authorization", "APPCODE "+ServerInfo.getAppCode());
- return headers;
- }
-
- //无网络
- private static void onNetDisabled(ResponseHandler responseHandler) {
- responseHandler.onStart();
- responseHandler.onFailure(0, -1, "网络连接异常");
- responseHandler.onFinish();
- }
-
- //完整url路径
- private static String getAbsolutUrl(String relativeUrl){
- if (TextUtils.isEmpty(relativeUrl)) {
- return ServerInfo.getServerAddress();
- }
- return ServerInfo.getServerAddress() + relativeUrl;
- }
-
- //参数
- private static RequestParams addCommonParams(RequestParams params) {
- if (params == null) {
- params = new RequestParams();
- }
- return params;
- }
-
-
- }
其中ResponseHandler是TextHttpResponseHandler的子类,主要就两个方法,onfailer以及onsuccess两个方法,返回值用了gson可指定返回bean。
- public abstract class ResponseHandler<T> extends TextHttpResponseHandler {
-
- private static final String TAG = "ResponseHandler";
- private static final int STATUS_OK = 200;
- public ResponseHandler() {
- this(null);
- }
- public ResponseHandler(Type resultType) {
- super();
- this.resultType = resultType;
- }
-
- public abstract void onFailure(int statusCode, int errorCode, String msg);
- public abstract void onSuccess(T result);
- private Type resultType;
- @Override
- public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
- Log.d(TAG, "<< 网络请求失败:" + responseString);
- String msg = null;
- int code=-1;
- if (statusCode != 0 && !TextUtils.isEmpty(responseString)) {
- try {
- JSONObject jsonObject = new JSONObject(responseString);
- code = jsonObject.getInt("code");
- msg = jsonObject.getString("message");
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- if (TextUtils.isEmpty(msg)) {
- msg = "网络请求失败";
- }
- onFailure(statusCode, code, msg);
-
- }
-
- @Override
- public void onSuccess(int statusCode, Header[] headers, String responseString) {
- if (statusCode!=STATUS_OK){
- onFailure(statusCode, headers, responseString, null);
- return;
- }
-
- Log.d(TAG, "<< 网络请求成功:" + responseString);
- if (TextUtils.isEmpty(responseString)) {
- onFailure(statusCode, -1, "返回数据异常");
- return;
- }
-
- Type type = getResultType();
- String className = TypeToken.get(type).getRawType().getName();
- if (className.equals(String.class.getName())) {
- onSuccess((T) responseString);
- return;
- }
- T result;
- try {
- result = new Gson().fromJson(responseString, type);
- } catch (Exception e) {
- e.printStackTrace();
- onFailure(statusCode,-1, "返回数据解析失败");
- return;
- }
- onSuccess(result);
- }
-
- private Type getResultType() {
- if (resultType == null) {
- Type[] types = ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments();
- resultType = types[0];
- }
- return resultType;
- }
- }
接下来是调用,我另外对各个调用方法进行了封装,如下:
- public static RequestHandle getExpressInfo(String orderId,String type,ResponseHandler responseHandler){
- RequestParams requestParams=new RequestParams();
- requestParams.put("no",orderId);
- requestParams.put("type",type);
- return HttpClient.doGet("cexpress",requestParams,responseHandler);
- }
调用时十分简单。
- RequestHandle requestHandle= ExpressApi.getExpressInfo("", "", new ResponseHandler<CourierBean>() {
-
- @Override
- public void onSuccess(CourierBean result) {
-
-
- }
-
- @Override
- public void onFailure(int statusCode, int errorCode, String msg) {
- Toast.makeText(MainActivity.this,msg+"--"+errorCode,Toast.LENGTH_SHORT).show();
- }
- });
这里封装的httpclient十分简单,如果有需要还可以封装更多的请求方法,比如上传文件
- public static RequestHandle postBringImage(String relativeUrl,
- RequestParams params,
- ResponseHandler responseHandler,
- String filesKey,
- File... files) throws FileNotFoundException {
- params = addCommonParams(params);
- if (files != null && files.length > 0) {
- params.put(filesKey, files, "image/*", null);
- params.setAutoCloseInputStreams(true);
- }
- params.setForceMultipartEntityContentType(true);
- JLog.d(TAG, ">> 发起POST请求...");
- String url = getAbsoluteUrl(relativeUrl);
- JLog.d(TAG, ">> 请求地址:" + url);
- JLog.d(TAG, ">> 请求参数:" + params.toString());
- if (NetUtils.hasNetwork(App.getInstance())) {
- return ASYNC_CLIENT.post(null, url, getCommonHeader(), params, null, responseHandler);
- } else {
- JLog.v(TAG, ">> 网络连接异常");
- onNetDisabled(responseHandler);
- return null;
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。