从零开始写Http框架---第四篇

本篇概述:
网络请求失败或者异常时,回调onFailed()方法
改动如下代码:
1 
//响应码>=300,即为失败
            if (urlConnection.getResponseCode() >= 300) {
                String msg = urlConnection.getResponseMessage();
                callBack.onFailed(msg);
            }else {
                callBack.onSuccess(null, object);
}

2 捕获异常时处理:

callBack.onFailed("请求异常");
整体代码:
/**
 * 任务线程类
 * @author lincoln
 *
 */
public class HttpTask implements Runnable{  
    private String rootUrl;
    private LincolnCallBack callBack;
    private HttpMethod method;
    private RequestParams params;

    public HttpTask(String rootUrl,HttpMethod method,RequestParams params,LincolnCallBack callback){
        this.rootUrl = rootUrl;
        this.callBack = callback;
        this.params = params;
        this.method = method;
    }

    public void sendRequest(){
        try {
            URL url = new URL(rootUrl);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod(method.toString());
            if (method != HttpMethod.GET) {
                urlConnection.setDoOutput(true);
                byte[] bytes = params.toString().getBytes();
                urlConnection.getOutputStream().write(bytes);
            }

            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();
            ByteArrayOutputStream byteOutSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int length = -1;
            while ((length = inputStream.read(buffer)) != -1) {
                byteOutSteam.write(buffer, 0, length);
            }
            String resultString = byteOutSteam.toString();
            JSONObject object = new JSONObject(resultString);
            //响应码>=300,即为失败
            if (urlConnection.getResponseCode() >= 300) {
                String msg = urlConnection.getResponseMessage();
                callBack.onFailed(msg);
            }else {
                callBack.onSuccess(null, object);
            }
        } catch (Exception e) {
            e.printStackTrace();
            callBack.onFailed("请求异常");
        }

    }

    @Override
    public void run() {
        sendRequest();
    }

}

查看源码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值