AsyncClientUtils

package com.ndkj.jsxt.common.utils;

import android.content.Context;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.ndkj.jsxt.common.adapter.http.BaseJsonHttpResponseAdapter;
import com.ndkj.jsxt.common.callbackinf.HttpPostHandler;
import com.ndkj.jsxt.common.entity.HttpResponseBean;
import com.ndkj.jsxt.constants.AppConstants;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * Created by Administrator on 2015/10/22.
 */
public class AsyncClientUtils {
    private static RequestQueue requestQueue;

    private static RequestQueue getInstance(Context context) {
        if (!Utils.isNetworkConnected(context)) {
            ToastUtils.show(context, "网络未设置好");
            return null;
        }
        if (requestQueue == null) {
            requestQueue = Volley.newRequestQueue(context);
        }
        return requestQueue;
    }

    /**
     * 以字符串的形式发送post请求
     *
     * @param reqBody                     请求体
     * @param url                         请求的路径
     * @param baseJsonHttpResponseAdapter 返回数据形式的适配器
     * @param handler                     返回数据的处理器
     */
    public static void stringPost(final Map reqBody, String url, final BaseJsonHttpResponseAdapter baseJsonHttpResponseAdapter, final HttpPostHandler handler) {

        getInstance(baseJsonHttpResponseAdapter.context);
        if (requestQueue == null) {
            return;
        }
        final StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                LOG.e("login", "----------------------->" + response);
                if (TextUtils.isEmpty(response) == false) {
                    //替换网页端的换行
                    response = response.replaceAll("&lt;br&gt;", "\n");
                    try {
                        baseJsonHttpResponseAdapter.responseBean = (HttpResponseBean) JSON.parseObject(response, HttpResponseBean.class);
                        String resultStr = baseJsonHttpResponseAdapter.responseBean.getRows();
                        if (Utils.isNotEmpty(resultStr)) {
                            if (baseJsonHttpResponseAdapter.requestType == 1) {
                                baseJsonHttpResponseAdapter.responseBean.setResultBean(JSON.parseObject(resultStr, baseJsonHttpResponseAdapter.resultClazz));
                            } else if (baseJsonHttpResponseAdapter.requestType == 2) {
                                baseJsonHttpResponseAdapter.responseBean.setResultList(JSON.parseArray(resultStr, baseJsonHttpResponseAdapter.resultClazz));
                            }
                        }
                        handler.postSuccessful(baseJsonHttpResponseAdapter.responseBean);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                AlertDialogUtils.hideDialog();
                try {
                    handler.postError(error);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }) {
            /**
             * 此方法设置请求的头文件信息
             * @return
             * @throws AuthFailureError
             */
//            public Map<String, String> getHeaders() throws AuthFailureError {
//                Map<String, String> map = new HashMap<String, String>();
//                map.put("Content-Type", "application/x-www-form-urldecoded");
//                return map;
//            }

            /**
             * 设置请求的参数
             * @return
             * @throws AuthFailureError
             */
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                LOG.e("listsize", reqBody.toString());
                Set set = reqBody.keySet();
                Iterator iterator = set.iterator();
                while (iterator.hasNext()) {
                    Object paramKey = iterator.next();
                    if (paramKey != null) {
                        reqBody.put(paramKey, reqBody.get(paramKey).toString().replaceAll("\n", "&lt;br&gt;"));
                    }
                }
                return reqBody;
            }
        };
        requestQueue.add(request);
    }

    /**
     * 以字符串的形式发送post请求
     *
     * @param reqBody                     请求体
     * @param url                         请求的路径
     * @param baseJsonHttpResponseAdapter 返回数据形式的适配器
     * @param handler                     返回数据的处理器
     */
    public static void stringPostShowDialog(final Map reqBody, String url, final BaseJsonHttpResponseAdapter baseJsonHttpResponseAdapter, final HttpPostHandler handler) {

        getInstance(baseJsonHttpResponseAdapter.context);
        if (requestQueue == null) {
            return;
        }
        AlertDialogUtils.showDialog();
        final StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                AlertDialogUtils.hideDialog();
                if (TextUtils.isEmpty(response) == false) {
                    LOG.e("login", "----------------------->" + response);
                    //替换网页端的换行
                    response = response.replaceAll("&lt;br&gt;", "\n");
                    try {
                        baseJsonHttpResponseAdapter.responseBean = (HttpResponseBean) JSON.parseObject(response, HttpResponseBean.class);
                        String resultStr = baseJsonHttpResponseAdapter.responseBean.getRows();
                        if (Utils.isNotEmpty(resultStr)) {
                            if (baseJsonHttpResponseAdapter.requestType == 1) {
                                baseJsonHttpResponseAdapter.responseBean.setResultBean(JSON.parseObject(resultStr, baseJsonHttpResponseAdapter.resultClazz));
                            } else if (baseJsonHttpResponseAdapter.requestType == 2) {
                                baseJsonHttpResponseAdapter.responseBean.setResultList(JSON.parseArray(resultStr, baseJsonHttpResponseAdapter.resultClazz));
                            }
                        }
                        handler.postSuccessful(baseJsonHttpResponseAdapter.responseBean);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                AlertDialogUtils.hideDialog();
                try {
                    handler.postError(error);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }) {
            /**
             * 此方法设置请求的头文件信息
             * @return
             * @throws AuthFailureError
             */
//            public Map<String, String> getHeaders() throws AuthFailureError {
//                Map<String, String> map = new HashMap<String, String>();
//                map.put("Content-Type", "application/x-www-form-urldecoded");
//                return map;
//            }

            /**
             * 设置请求的参数
             * @return
             * @throws AuthFailureError
             */
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                LOG.e("listsize", reqBody.toString());
                Set set = reqBody.keySet();
                Iterator iterator = set.iterator();
                while (iterator.hasNext()) {
                    Object paramKey = iterator.next();
                    if (paramKey != null) {
                        reqBody.put(paramKey, reqBody.get(paramKey).toString().replaceAll("\n", "&lt;br&gt;"));
                    }
                }
                return reqBody;
            }
        };
        requestQueue.add(request);
    }

    private static <T> void basePost(T reqBody, final String url, final BaseJsonHttpResponseAdapter baseJsonHttpResponseAdapter, final HttpPostHandler handler) {

        getInstance(baseJsonHttpResponseAdapter.context);
        if (requestQueue == null) {
            return;
        }

        final JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, getRequestBody(reqBody), new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

                if (response != null) {
                    baseJsonHttpResponseAdapter.responseBean = JSON.parseObject(response.toString(), HttpResponseBean.class);
                    String result = baseJsonHttpResponseAdapter.responseBean.getRows();
                    if (Utils.isNotEmpty(result)) {
                        if (baseJsonHttpResponseAdapter.requestType == 1) {
                            baseJsonHttpResponseAdapter.responseBean.setResultBean(JSON.parseObject(result, baseJsonHttpResponseAdapter.resultClazz));
                        } else if (baseJsonHttpResponseAdapter.requestType == 2) {
                            baseJsonHttpResponseAdapter.responseBean.setResultList(JSON.parseArray(result, baseJsonHttpResponseAdapter.resultClazz));
                        }
                    }
                    handler.postSuccessful(baseJsonHttpResponseAdapter.responseBean);
                }
            }

        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        handler.postError(error);
                    }
                });
//        {
        /**
         * 此方法设置请求的头文件信息
         * @return
         * @throws AuthFailureError
         */
//            public Map<String, String> getHeaders() throws AuthFailureError {
//                Map<String, String> map = new HashMap<String, String>();
//                map.put("Content-Type", "application/x-www-form-urldecoded");
//                return map;
//            }
//        };
        LOG.e("Testurl", new String(request.getPostBody()));
        requestQueue.add(request);
    }

    /**
     * 通过get方式请求数据
     *
     * @param url                         请求路径
     * @param baseJsonHttpResponseAdapter 返回数据的适配器
     * @param handler                     请求结果的处理器
     */
    public static void reqDataByGet(String url, BaseJsonHttpResponseAdapter baseJsonHttpResponseAdapter, HttpPostHandler handler) {
        basePost(null, url, baseJsonHttpResponseAdapter, handler);
    }

    /**
     * 通过post方式提交数据
     *
     * @param reqBody                     提交的数据体
     * @param url                         请求路径
     * @param baseJsonHttpResponseAdapter 返回数据的适配器
     * @param handler                     请求结果的处理器
     * @param <T>
     */
    public static <T> void reqDataByPost(T reqBody, String url, BaseJsonHttpResponseAdapter baseJsonHttpResponseAdapter, HttpPostHandler handler) {
        basePost(reqBody, url, baseJsonHttpResponseAdapter, handler);
    }

    /**
     * 获得请求体的数据
     *
     * @param reqBody 请求体
     * @return
     */
    private static <T> JSONObject getRequestBody(T reqBody) {
        JSONObject jsonObject = null;
        //对值进行过滤,确保在提交数据是出现缺少字段的错误
        ValueFilter filter = new ValueFilter() {
            @Override
            public Object process(Object object, String name, Object value) {
                return value == null ? "" : value;
            }
        };
        if (reqBody == null) {
            return jsonObject;
        } else {
            //请求头文件已经在请求的方法中实现了,所以这里不需要添加了了
            //如果全部用json来处理数据那就添加head字段
//            new HttpRequestBean<>(null, reqBody)
            String reqBodyJson = JSON.toJSONString(reqBody, filter);
            try {
                jsonObject = new JSONObject(reqBodyJson);
                LOG.e("Token", jsonObject.toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return jsonObject;

    }

    /**
     * 取消所有请求
     */
    public static void  cancleAllRequest() {
        getInstance(AppConstants.CONTEXT);
        if (requestQueue == null) {
            return;
        }
        requestQueue.cancelAll(new RequestQueue.RequestFilter() {
            @Override
            public boolean apply(Request<?> request) {
                return true;
            }
        });
    }

}
时间: 2024-10-07 20:15:02

AsyncClientUtils的相关文章