[Android]【安卓】HTTP请求框架的使用

[Android]【安卓】HTTP请求框架的使用

本篇博客已收录到我的安卓开发小结中——点击【安卓开发小结】
1、在build.gradle中添加libs依赖
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'org.greenrobot:eventbus:3.0.0'
}
2、引入第三方库

这里写图片描述

3、写一个HttpResult类
public class HttpResult {

    /*API编码*/
    private String apiNo;
    /*原始请求地址*/
    private String url;
    /*原始JSON字符串*/
    private String result;
    /*原始JSON字符串*/
    private JSONObject jsonResult;
    /*传递跟踪信息*/
    private Map<String, String> extras;
    /*API请求结果*/
    private boolean error = false;

    public HttpResult(String apiNo, String url, String result) {
        super();
        this.apiNo = apiNo;
        this.url = url;
        this.result = result;
        try {
            JSONObject jsonObject = new JSONObject(result);
            this.setJsonResult(jsonObject);
        } catch (JSONException e) {

        }
    }

    public HttpResult(String apiNo, String url, String result, Map<String, String> extras) {
        super();
        this.apiNo = apiNo;
        this.url = url;
        this.result = result;
        this.extras = extras;
    }

    public String getApiNo() {
        return apiNo;
    }

    public void setApiNo(String apiNo) {
        this.apiNo = apiNo;
    }

    public Map<String, String> getExtras() {
        return extras;
    }

    public void setExtras(Map<String, String> extras) {
        this.extras = extras;
    }

    public boolean isError() {
        return error;
    }

    public void setError(boolean isError) {
        this.error = isError;
    }

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }

    public JSONObject getJsonResult() {
        return jsonResult;
    }

    public void setJsonResult(JSONObject jsonResult) {
        this.jsonResult = jsonResult;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    @Override
    public String toString() {
        StringBuffer sb = new StringBuffer();
        sb.append(apiNo);
        sb.append("|");
        sb.append(url);
        sb.append("|");
        sb.append(result);
        sb.append("|");
        sb.append(error);
        return sb.toString();
    }

}
4、写一个HttpRequestEvent 类和HttpRequestErrorEvent 类
public class HttpRequestEvent {

    /** 请求结果 */
    public final HttpResult httpResult;
    /**
     * 构造方法
     * @param httpResult
     */
    public HttpRequestEvent(HttpResult httpResult) {
        this.httpResult = httpResult;
    }

    /**
     * 获取请求结果
     * @return
     */
    public HttpResult getResult() {
        return httpResult;
    }


}
public class HttpRequestErrorEvent {
    /** 请求结果 */
    public final HttpResult httpResult;

    /** 异常 */
    public HttpException exception;

    /**
     * 构造方法
     * @param httpResult
     */
    public HttpRequestErrorEvent(HttpResult httpResult) {
        this.httpResult = httpResult;
    }

    /**
     * 获取请求结果
     * @return
     */
    public HttpResult getResult() {
        return httpResult;
    }

    public HttpException getException() {
        return exception;
    }

    public void setException(HttpException exception) {
        this.exception = exception;
    }
}
5、写一个HttpHelper类
public class HttpHelper {
    private static HttpUtils httpInstance = null;
    private static HashMap<String, HttpHandler> httpHandlerList = new HashMap<>();
    /**
     * 清除所有正在請求的http
     */
    public static void clearHttp() {
        Iterator iter = httpHandlerList.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            HttpHandler val = (HttpHandler) entry.getValue();
            val.cancel();
        }
        httpHandlerList.clear();
    }

    /**
     * 默认超时时间 10秒
     */
    private static int TIME_OUT = 10000;

    public static HttpUtils getHttpInstance() {
        if (httpInstance == null) {
            httpInstance = new HttpUtils(10000);
            httpInstance.configDefaultHttpCacheExpiry(100);
            httpInstance.configTimeout(TIME_OUT);
            httpInstance.configSoTimeout(TIME_OUT);
            httpInstance.configRequestThreadPoolSize(20);
            httpHandlerList = new HashMap<>();
        }
        return httpInstance;
    }

    /**
     * GET 请求
     *
     * @param url   API地址
     * @param apiNo API编号
     */
    public static void get(final String url, final String apiNo) {
        get(url, apiNo, null, null);
    }

    /**
     * GET 请求
     *
     * @param url    API地址
     * @param apiNo  API编号
     * @param extras 跟踪参数
     */
    public static void get(final String url, final String apiNo, final Map<String, String> extras) {
        get(url, apiNo, null, extras);
    }

    /**
     * GET 请求
     *
     * @param url    API地址
     * @param params URL参数
     * @param apiNo  API编号
     * @param extras 跟踪参数
     */
    public static void get(final String url, final String apiNo, final Map<String, String> params, final Map<String, String> extras) {
        RequestParams rp = new RequestParams();
        if (null != params) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                rp.addQueryStringParameter(entry.getKey(), entry.getValue());
            }
        }
        String yourToken = "";
        rp.addHeader("Access-Token",yourToken);
        httpHandlerList.put(apiNo, getHttpInstance().send(HttpRequest.HttpMethod.GET, url, rp, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                successHandler(url, apiNo, params, extras, responseInfo.result);
            }
            @Override
            public void onFailure(HttpException error, String msg) {
                failureHandler(url, apiNo, params, extras, error, msg);
            }
        }));
    }

    /**
     * POST 请求
     *
     * @param url   API地址
     * @param apiNo API编号
     */
    public static void post(final String url, final String apiNo) {
        post(url, apiNo, null, null, null);
    }

    /**
     * POST 请求
     *
     * @param url      API地址
     * @param apiNo    API编号
     * @param jsonData JSON数据
     */
    public static void post(final String url, final String apiNo, String jsonData) {
        post(url, apiNo, jsonData, null, null);
    }

    /**
     * POST 请求
     *
     * @param url      API地址
     * @param apiNo    API编号
     * @param jsonData JSON数据
     * @param extras   跟踪参数
     */
    public static void post(final String url, final String apiNo, String jsonData, final Map<String, String> extras) {
        post(url, apiNo, jsonData, null, extras);
    }

    /**
     * POST 请求
     *
     * @param url    API地址
     * @param params URL参数
     * @param apiNo  API编号
     * @param extras 跟踪参数
     */
    public static void post(final String url, final String apiNo, final Map<String, String> params, final Map<String, String> extras) {
        post(url, apiNo, null, params, extras);
    }

    /**
     * POST 请求
     *
     * @param url      API地址
     * @param params   URL参数
     * @param apiNo    API编号
     * @param jsonData JSON数据
     * @param extras   跟踪参数
     */
    public static void post(final String url, final String apiNo, String jsonData, final Map<String, String> params, final Map<String, String> extras) {
        RequestParams rp = new RequestParams();
        if (null != params) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                rp.addQueryStringParameter(entry.getKey(), entry.getValue());
            }
        }

        if (null != jsonData) {
            try {
                rp.setBodyEntity(new StringEntity(jsonData, "utf-8"));
                rp.setContentType("application/json;charset=utf-8");
            } catch (Exception e) {
                //TODO: 日志
            }
        }

        String yourToken = "";
        rp.addHeader("Access-Token",yourToken);

        httpHandlerList.put(apiNo, getHttpInstance().send(HttpRequest.HttpMethod.POST, url, rp, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                successHandler(url, apiNo, params, extras, responseInfo.result);
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                failureHandler(url, apiNo, params, extras, error, msg);
            }


        }));
    }

    /**
     * CURD 请求成功回调
     *
     * @param url
     * @param params
     * @param apiNo
     * @param extras
     * @param responseResult
     */
    private static void successHandler(final String url, final String apiNo, Map<String, String> params, final Map<String, String> extras, String responseResult) {
        HttpResult httpResult = new HttpResult(apiNo, url, responseResult, extras);
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(responseResult);
            httpResult.setJsonResult(jsonObject);
            if (jsonObject.has("status")&&200 == jsonObject.getInt("status")) {
                EventBus.getDefault().post(new HttpRequestEvent(httpResult));
            } else {
                EventBus.getDefault().post(new HttpRequestErrorEvent(httpResult));
            }
        } catch (JSONException e) {

        }

        if (httpHandlerList.containsKey(url)) {
            httpHandlerList.remove(url);
        }
    }

    /**
     * CURD 请求失败回调
     *
     * @param url
     * @param params
     * @param apiNo
     * @param extras
     * @param error
     * @param msg
     */
    private static void failureHandler(final String url, final String apiNo, Map<String, String> params, final Map<String, String> extras, HttpException error, String msg) {
        HttpResult httpResult = new HttpResult(apiNo, url, msg, extras);
        httpResult.setError(true);
        HttpRequestErrorEvent httpRequestErrorEvent = new HttpRequestErrorEvent(httpResult);
        httpRequestErrorEvent.setException(error);
        EventBus.getDefault().post(httpRequestErrorEvent);
        if (httpHandlerList.containsKey(url)) {
            httpHandlerList.remove(url);
        }
    }

}
6、在MainActivity中试验Post请求
public class MainActivity extends AppCompatActivity{

    TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView)findViewById(R.id.textView);
        EventBus.getDefault().register(this);
        String url = "";
        String devicePid = "";
        getDeviceViewCarrouselId(url,devicePid);
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    public void getDeviceViewCarrouselId(String url , String deviceRecipeId) {
            try {
                JSONObject json = new JSONObject();
                JSONObject subJson1 = new JSONObject();
                JSONObject subJson2 = new JSONObject();
                json.put("limit",10);
                json.put("offset",0);
                subJson1.put("_id",deviceRecipeId);
                json.put("query",subJson1);
                subJson2.put("create_time",-1);
                json.put("order",subJson2);
                post(url, "apiNo_key", json.toString());
            } catch (Exception e) {

            }
    }

    /**
     * http请求成功处理
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(HttpRequestEvent event) {

    }

    /**
     * http请求失败处理
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(HttpRequestErrorEvent event) {
        HttpResult httpResult = event.getResult();
        String apiNo = httpResult.getApiNo();
        String result = httpResult.getResult();
        switch (apiNo) {
            case "apiNo_key":
                textView.setText(result);
                break;
        }
    }

}

结果:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/Hystudio_lzu/article/details/80153501