当前位置:   article > 正文

AsyncHttpClient使用总结_asynchttpclient requestparams

asynchttpclient requestparams

    最近项目中网络请求使用的AsyncHttpClient,这里简单总结下使用方法,既加强记忆,有能和大家分享下。

1:项目导入

implementation 'com.loopj.android:android-async-http:1.4.9'

2:直接调用

  1. //创建实例
  2. AsyncHttpClient client=new AsyncHttpClient();
  3. //
  4. client.get(this, "", new TextHttpResponseHandler() {
  5. @Override
  6. public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
  7. }
  8. @Override
  9. public void onSuccess(int statusCode, Header[] headers, String responseString) {
  10. }
  11. });

 直接调用十分简单,如上述代码。

3:简易封装

直接调用看似十分简单,但当接口数量增大时,整个代码会十分繁琐,因为每个类都要重复创建实例,调用方法。所以封装起来很有必要,首先我们封装一个httpClient类,

  1. public class HttpClient {
  2. private static final String TAG = "HttpClient";
  3. //contentType
  4. private static final String CONTENT_TYPE_FORM = "application/x-www-form-urlencoded";
  5. //创建实例
  6. private static final AsyncHttpClient ASYNC_CLIENT = new AsyncHttpClient();
  7. //可在此处配置header,例如机型,版本号,umengType等
  8. static {
  9. ASYNC_CLIENT.setTimeout(20000);
  10. }
  11. //get方法
  12. //ResponseHandler 是TextHttpResponseHandler的子类,下面会有介绍
  13. public static RequestHandle doGet(String relativeUrl, RequestParams params, ResponseHandler responseHandler){
  14. params=addCommonParams(params);
  15. //完整url
  16. String url=getAbsolutUrl(relativeUrl);
  17. //在此处添加网络监测
  18. if (NetUtils.hasNetwork(App.getInstance())){
  19. return ASYNC_CLIENT.get(null,url,getCommonHeader(),params,responseHandler);
  20. }else{
  21. Log.v(TAG, ">> 网络连接异常");
  22. onNetDisabled(responseHandler);
  23. return null;
  24. }
  25. }
  26. public static RequestHandle doPost(String relativeUrl, RequestParams params, ResponseHandler responseHandler){
  27. params=addCommonParams(params);
  28. String url=getAbsolutUrl(relativeUrl);
  29. if (NetUtils.hasNetwork(App.getInstance())){
  30. return ASYNC_CLIENT.post(null,url,getCommonHeader(),params,CONTENT_TYPE_FORM,responseHandler);
  31. }else{
  32. Log.v(TAG, ">> 网络连接异常");
  33. onNetDisabled(responseHandler);
  34. return null;
  35. }
  36. }
  37. //阿里云全国物流快递查询(单号识别)
  38. public static Header[] getCommonHeader(){
  39. Header[] headers = new BasicHeader[1];
  40. headers[0]=new BasicHeader("Authorization", "APPCODE "+ServerInfo.getAppCode());
  41. return headers;
  42. }
  43. //无网络
  44. private static void onNetDisabled(ResponseHandler responseHandler) {
  45. responseHandler.onStart();
  46. responseHandler.onFailure(0, -1, "网络连接异常");
  47. responseHandler.onFinish();
  48. }
  49. //完整url路径
  50. private static String getAbsolutUrl(String relativeUrl){
  51. if (TextUtils.isEmpty(relativeUrl)) {
  52. return ServerInfo.getServerAddress();
  53. }
  54. return ServerInfo.getServerAddress() + relativeUrl;
  55. }
  56. //参数
  57. private static RequestParams addCommonParams(RequestParams params) {
  58. if (params == null) {
  59. params = new RequestParams();
  60. }
  61. return params;
  62. }
  63. }

 其中ResponseHandler是TextHttpResponseHandler的子类,主要就两个方法,onfailer以及onsuccess两个方法,返回值用了gson可指定返回bean。

  1. public abstract class ResponseHandler<T> extends TextHttpResponseHandler {
  2. private static final String TAG = "ResponseHandler";
  3. private static final int STATUS_OK = 200;
  4. public ResponseHandler() {
  5. this(null);
  6. }
  7. public ResponseHandler(Type resultType) {
  8. super();
  9. this.resultType = resultType;
  10. }
  11. public abstract void onFailure(int statusCode, int errorCode, String msg);
  12. public abstract void onSuccess(T result);
  13. private Type resultType;
  14. @Override
  15. public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
  16. Log.d(TAG, "<< 网络请求失败:" + responseString);
  17. String msg = null;
  18. int code=-1;
  19. if (statusCode != 0 && !TextUtils.isEmpty(responseString)) {
  20. try {
  21. JSONObject jsonObject = new JSONObject(responseString);
  22. code = jsonObject.getInt("code");
  23. msg = jsonObject.getString("message");
  24. } catch (Exception e) {
  25. e.printStackTrace();
  26. }
  27. }
  28. if (TextUtils.isEmpty(msg)) {
  29. msg = "网络请求失败";
  30. }
  31. onFailure(statusCode, code, msg);
  32. }
  33. @Override
  34. public void onSuccess(int statusCode, Header[] headers, String responseString) {
  35. if (statusCode!=STATUS_OK){
  36. onFailure(statusCode, headers, responseString, null);
  37. return;
  38. }
  39. Log.d(TAG, "<< 网络请求成功:" + responseString);
  40. if (TextUtils.isEmpty(responseString)) {
  41. onFailure(statusCode, -1, "返回数据异常");
  42. return;
  43. }
  44. Type type = getResultType();
  45. String className = TypeToken.get(type).getRawType().getName();
  46. if (className.equals(String.class.getName())) {
  47. onSuccess((T) responseString);
  48. return;
  49. }
  50. T result;
  51. try {
  52. result = new Gson().fromJson(responseString, type);
  53. } catch (Exception e) {
  54. e.printStackTrace();
  55. onFailure(statusCode,-1, "返回数据解析失败");
  56. return;
  57. }
  58. onSuccess(result);
  59. }
  60. private Type getResultType() {
  61. if (resultType == null) {
  62. Type[] types = ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments();
  63. resultType = types[0];
  64. }
  65. return resultType;
  66. }
  67. }

 接下来是调用,我另外对各个调用方法进行了封装,如下:

  1. public static RequestHandle getExpressInfo(String orderId,String type,ResponseHandler responseHandler){
  2. RequestParams requestParams=new RequestParams();
  3. requestParams.put("no",orderId);
  4. requestParams.put("type",type);
  5. return HttpClient.doGet("cexpress",requestParams,responseHandler);
  6. }
调用时十分简单。
  1. RequestHandle requestHandle= ExpressApi.getExpressInfo("", "", new ResponseHandler<CourierBean>() {
  2. @Override
  3. public void onSuccess(CourierBean result) {
  4. }
  5. @Override
  6. public void onFailure(int statusCode, int errorCode, String msg) {
  7. Toast.makeText(MainActivity.this,msg+"--"+errorCode,Toast.LENGTH_SHORT).show();
  8. }
  9. });

这里封装的httpclient十分简单,如果有需要还可以封装更多的请求方法,比如上传文件

  1. public static RequestHandle postBringImage(String relativeUrl,
  2. RequestParams params,
  3. ResponseHandler responseHandler,
  4. String filesKey,
  5. File... files) throws FileNotFoundException {
  6. params = addCommonParams(params);
  7. if (files != null && files.length > 0) {
  8. params.put(filesKey, files, "image/*", null);
  9. params.setAutoCloseInputStreams(true);
  10. }
  11. params.setForceMultipartEntityContentType(true);
  12. JLog.d(TAG, ">> 发起POST请求...");
  13. String url = getAbsoluteUrl(relativeUrl);
  14. JLog.d(TAG, ">> 请求地址:" + url);
  15. JLog.d(TAG, ">> 请求参数:" + params.toString());
  16. if (NetUtils.hasNetwork(App.getInstance())) {
  17. return ASYNC_CLIENT.post(null, url, getCommonHeader(), params, null, responseHandler);
  18. } else {
  19. JLog.v(TAG, ">> 网络连接异常");
  20. onNetDisabled(responseHandler);
  21. return null;
  22. }
  23. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/413615
推荐阅读
相关标签
  

闽ICP备14008679号