欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

NoHttp封装--01

程序员文章站 2023-11-06 10:26:10
NoHttpActivity CallServer: ResponseListener: HttpCallBack FastJsonRequest:自定义FastJsonRequest对象,所有的自定义对象都要继承{@link RestReqeust} WaitDialog: Constants ......

NoHttpActivity

 1 public class NoHttpActivity extends Activity implements View.OnClickListener {
 2 
 3     private final int NOHTTP_LOGIN = 0x01;//登陆
 4     private final int NOHTTP_LOGOUT = 0x02;//退出
 5 
 6     private TextView tvResult;
 7 
 8     @Override
 9     protected void onCreate(Bundle savedInstanceState) {
10         super.onCreate(savedInstanceState);
11         setContentView(R.layout.activity_nohttp);
12         findViewById(R.id.btn_login).setOnClickListener(this);
13         findViewById(R.id.btn_logout).setOnClickListener(this);
14         tvResult = (TextView) findViewById(R.id.tv_result);
15     }
16 
17     @Override
18     public void onClick(View v) {
19         if (v.getId() == R.id.btn_login) {
20             FastJsonRequest request = new FastJsonRequest(Constants.LOGIN, RequestMethod.GET);
21             request.add("userName", "yolanda");
22             request.add("userPwd", "123");
23             CallServer.getInstance().add(this, request, callBack, NOHTTP_LOGIN, true, false, true);
24         } else {
25             FastJsonRequest request = new FastJsonRequest(Constants.LOGOUT, RequestMethod.GET);
26             CallServer.getInstance().add(this, request, callBack, NOHTTP_LOGOUT, true, false, true);
27         }
28     }
29 
30     private HttpCallBack<JSONObject> callBack = new HttpCallBack<JSONObject>() {
31 
32         @Override
33         public void onSucceed(int what, Response<JSONObject> response) {
34             if (what == NOHTTP_LOGIN) {// 处理登录结果
35                 JSONObject jsonObject = response.get();
36                 tvResult.setText("登录接口数据:" + jsonObject.getString("data"));
37             } else if (what == NOHTTP_LOGOUT) {// 处理登出结果
38                 JSONObject jsonObject = response.get();
39                 tvResult.setText("退出接口数据:" + jsonObject.getString("data"));
40             }
41         }
42 
43         @Override
44         public void onFailed(int what, String url, Object tag, Exception exception, int responseCode, long networkMillis) {
45             tvResult.setText("请求失败");
46         }
47     };
48 
49 }

CallServer:

 1 public class CallServer {
 2 
 3     private static CallServer instance;
 4 
 5     private RequestQueue queue;
 6 
 7     public synchronized static CallServer getInstance() {
 8         if (instance == null) {
 9             instance = new CallServer();
10         }
11         return instance;
12     }
13 
14     private CallServer() {
15         queue = NoHttp.newRequestQueue();
16     }
17 
18     /**
19      * 添加一个请求到请求队列
20      * 
21      * @param context 上下文
22      * @param request 请求对象
23      * @param callBack 接受回调结果
24      * @param what what,当多个请求用同一个responseListener接受结果时,用来区分请求
25      * @param isShowDialog 是否显示dialog
26      * @param isCanCancel 请求是否能被用户取消
27      * @param isShowError 是否提示用户错误信息
28      */
29     public <T> void add(Context context, Request<T> request, HttpCallBack<T> callBack, int what, boolean isShowDialog, boolean isCanCancel, boolean isShowError) {
30         queue.add(what, request, new ResponseListener<T>(request, context, callBack, isShowDialog, isCanCancel, isShowError));
31     }
32 
33 }

ResponseListener:

 1 public class ResponseListener<T> implements OnResponseListener<T> {
 2 
 3     private Request<T> mRequest;
 4 
 5     private WaitDialog mDialog;
 6 
 7     private HttpCallBack<T> callBack;
 8 
 9     private boolean isShowError;
10 
11     public ResponseListener(Request<T> request, Context context, HttpCallBack<T> callBack, boolean isShowDialog, boolean isCanCancel, boolean isShowError) {
12         this.mRequest = request;
13         this.callBack = callBack;
14         this.isShowError = isShowError;
15         if (context != null && isShowDialog) {
16             mDialog = new WaitDialog(context);
17             mDialog.setCancelable(isCanCancel);
18             mDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
19                 @Override
20                 public void onCancel(DialogInterface dialog) {
21                     mRequest.cancel(true);
22                 }
23             });
24         }
25     }
26 
27     @Override
28     public void onStart(int what) {
29         if (mDialog != null && !mDialog.isShowing())
30             mDialog.show();
31     }
32 
33     @Override
34     public void onSucceed(int what, Response<T> response) {
35         if (callBack != null)
36             callBack.onSucceed(what, response);
37     }
38 
39     @Override
40     public void onFailed(int what, String url, Object tag, Exception exception, int responseCode, long networkMillis) {
41         if (isShowError) {
42             if (exception instanceof ClientError) {// 客户端错误
43                 Toast.show("客户端发生错误");
44             } else if (exception instanceof ServerError) {// 服务器错误
45                 Toast.show("服务器发生错误");
46             } else if (exception instanceof NetworkError) {// 网络不好
47                 Toast.show("请检查网络");
48             } else if (exception instanceof TimeoutError) {// 请求超时
49                 Toast.show("请求超时,网络不好或者服务器不稳定");
50             } else if (exception instanceof UnKnownHostError) {// 找不到服务器
51                 Toast.show("未发现指定服务器");
52             } else if (exception instanceof URLError) {// URL是错的
53                 Toast.show("URL错误");
54             } else if (exception instanceof NotFoundCacheError) {
55                 Toast.show("没有发现缓存");
56             } else {
57                 Toast.show("未知错误");
58             }
59         }
60         if (callBack != null)
61             callBack.onFailed(what, url, tag, exception, responseCode, networkMillis);
62     }
63 
64     @Override
65     public void onFinish(int what) {
66         if (mDialog != null && mDialog.isShowing())
67             mDialog.dismiss();
68     }
69 
70 }

HttpCallBack

 1 public interface HttpCallBack<T> {
 2 
 3     /**
 4      * Server correct response to callback when an HTTP request.
 5      *
 6      * @param what the credit of the incoming request is used to distinguish between multiple requests.
 7      * @param response in response to the results.
 8      */
 9     void onSucceed(int what, Response<T> response);
10 
11     /**
12      * When there was an error correction.
13      *
14      * @param what the credit of the incoming request is used to distinguish between multiple requests.
15      * @param url url.
16      * @param tag tag of request callback.
17      * @param exception error message for request.
18      * @param responseCode server response code.
19      * @param networkMillis request process consumption time.
20      */
21     void onFailed(int what, String url, Object tag, Exception exception, int responseCode, long networkMillis);
22 
23 }

FastJsonRequest:自定义FastJsonRequest对象,所有的自定义对象都要继承{@link RestReqeust}

 1 public class FastJsonRequest extends RestRequest<JSONObject> {
 2 
 3     public FastJsonRequest(String url, RequestMethod requestMethod) {
 4         super(url, requestMethod);
 5     }
 6 
 7     public FastJsonRequest(String url) {
 8         super(url);
 9     }
10 
11     /**
12      * 高速服务端你能接受的数据类型是什么
13      */
14     @Override
15     public String getAccept() {
16         return JsonObjectRequest.ACCEPT;
17     }
18 
19     /**
20      * @param url 请求的url
21      * @param responseHeaders 服务端的响应头
22      * @param 服务端的响应数据
23      * @return 你解析后的对象
24      */
25     @Override
26     public JSONObject parseResponse(String url, Headers responseHeaders, byte[] responseBody) {
27         return parse(url, responseHeaders, responseBody);
28     }
29 
30     /**
31      * 解析服务端数据成{@link JsonObject}
32      * 
33      * @param url
34      * @param responseHeaders
35      * @param responseBody
36      * @return
37      */
38     public static JSONObject parse(String url, Headers responseHeaders, byte[] responseBody) {
39         String string = StringRequest.parseResponseString(url, responseHeaders, responseBody);
40         JSONObject jsonObject = null;
41         try {
42             jsonObject = JSON.parseObject(string);
43         } catch (Exception e) {// 可能返回的数据不是json,或者其他异常
44             string = "{}";
45             jsonObject = JSON.parseObject(string);
46         }
47         return jsonObject;
48     }
49 
50 }

WaitDialog:

 1 public class WaitDialog extends ProgressDialog {
 2 
 3     public WaitDialog(Context context) {
 4         super(context);
 5         requestWindowFeature(Window.FEATURE_NO_TITLE);
 6         setCanceledOnTouchOutside(false);
 7         setProgressStyle(STYLE_SPINNER);
 8         setMessage("正在请求,请稍候…");
 9     }
10 
11 }

 Constants

public class Constants {

    private static final String SERVER = "http://192.168.1.116/HttpServer/";

    /**
     * 登录接口
     */
    public static final String LOGIN = SERVER + "login";
    
    /**
     * 退出登录接口
     */
    public static final String LOGOUT = SERVER + "logout";

}