手寫HTTP網絡請求框架

創(chuàng)建基于HttpUrlConnection的具體獲取網絡數(shù)據(jù)流HttpUrlConnectionUtil

public class HttpUrlConnectionUtil {

    public static ByteArrayOutputStream execute(Request request) throws HttpException {
        switch (request.requestMethod) {
            case GET:
                return get(request);
            case POST:
                return post(request);
        }
        return null;
    }


    private static ByteArrayOutputStream get(Request request) throws HttpException {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(request.url).openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(15 * 1000);
            addHeaders(connection, request);

            if (HttpStatus.HTTP_OK == connection.getResponseCode()) {
                InputStream is = connection.getInputStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[2048];
                int len = 0;
                while (-1 != (len = is.read(buffer))) {
                    baos.write(buffer, 0, len);
                }
                baos.flush();
                baos.close();
                is.close();
                return baos;
            }
        } catch (MalformedURLException e) {
            throw new HttpException(HttpException.Status.XXX_EXCEPTION);
        } catch (ProtocolException e) {
            throw new HttpException(HttpException.Status.XXX_EXCEPTION);
        } catch (SocketTimeoutException e) {
            throw new HttpException(HttpException.Status.TIMEOUT_EXCEPTION);
        } catch (IOException e) {
            throw new HttpException(HttpException.Status.XXX_EXCEPTION);
        }
        throw new HttpException(HttpException.Status.XXX_EXCEPTION);
    }

    private static ByteArrayOutputStream post(Request request) throws HttpException {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(request.url).openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(15 * 1000);
            connection.setDoOutput(true);
            connection.setDoInput(true);

            addHeaders(connection, request);

            StringBuilder out = new StringBuilder();
            for (String key : request.body.keySet()) {
                if (out.length() != 0) {
                    out.append("&");
                }
                out.append(key).append("=").append(request.body.get(key));
            }
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(out.toString().getBytes());

            if (HttpStatus.HTTP_OK == connection.getResponseCode()) {
                InputStream is = connection.getInputStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[2048];
                int len = 0;
                while (-1 != (len = is.read(buffer))) {
                    baos.write(buffer, 0, len);
                }
                baos.flush();
                baos.close();
                is.close();
                return baos;
            }
        } catch (MalformedURLException e) {
            throw new HttpException(HttpException.Status.XXX_EXCEPTION);
        } catch (ProtocolException e) {
            throw new HttpException(HttpException.Status.XXX_EXCEPTION);
        } catch (SocketTimeoutException e) {
            throw new HttpException(HttpException.Status.TIMEOUT_EXCEPTION);
        } catch (IOException e) {
            throw new HttpException(HttpException.Status.XXX_EXCEPTION);
        }
        throw new HttpException(HttpException.Status.XXX_EXCEPTION);
    }


    private static void addHeaders(HttpURLConnection connection, Request request) {
        for (Map.Entry<String, String> header : request.headers.entrySet()) {
            connection.addRequestProperty(header.getKey(), header.getValue());
        }
    }


}

包裝具體每一個請求的Request類

public class Request {
    /**
     * 請求地址
     */
    public String url;
    /**
     * 請求form表單
     */
    public Map<String, String> body;
    /**
     * 請求頭
     */
    public Map<String, String> headers = new HashMap<>();
    /**
     * 請求方法
     */
    public RequestMethod requestMethod;
    /**
     * 請求回調
     */
    public AbsCallback callBack;

    /**
     * 請求重試次數(shù)
     */
    public int maxRequestCount = 3;

    public enum RequestMethod {GET, POST}

    public Request(String url, RequestMethod requestMethod) {
        this.url = url;
        this.requestMethod = requestMethod;
    }

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

    public Request setBody(Map<String, String> body) {
        this.body = body;
        return this;
    }

    public void setCallBack(AbsCallback callBack) {
        this.callBack = callBack;
    }
}

基于Handler旋圆、ThreadPoolExecutor線程池的異步請求處理類

public class RequestTask {
    private static final int MAIN_THREAD = 0x0001;
    private static InnerHandler handler = new InnerHandler();

    private final ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(5,
            Integer.MAX_VALUE,
            60 * 1000,
            TimeUnit.MILLISECONDS,
            new LinkedBlockingDeque<Runnable>(128));
    private Request request;

    public RequestTask(Request request) {
        this.request = request;
    }

    public void execute() {
        poolExecutor.execute(new Runnable() {
            @Override
            public void run() {
                Result result = request(0);
                Message message = handler.obtainMessage();
                message.obj = result;
                message.what = MAIN_THREAD;
                handler.sendMessage(message);

            }
        });
    }

    private Result request(int retry) {
        try {
            final ByteArrayOutputStream response = HttpUrlConnectionUtil.execute(request);
            return new Result(RequestTask.this, request.callBack.handleData(response));
        } catch (HttpException e) {
            if (e.type == HttpException.Status.TIMEOUT_EXCEPTION) {
                if (retry < request.maxRequestCount) {
                    retry++;
                    request(retry);
                }
            }
            return new Result(RequestTask.this, e);
        }
    }


    private static class InnerHandler extends Handler {
        private InnerHandler() {
            super(Looper.getMainLooper());
        }

        @Override
        public void handleMessage(Message msg) {
            Result result = (Result) msg.obj;
            switch (msg.what) {
                case MAIN_THREAD:
                    if (result.response instanceof Exception) {
                        result.requestTask.request.callBack.failure((Exception) result.response);
                        return;
                    }
                    result.requestTask.request.callBack.sucess(result.response);
            }
        }
    }

    private static class Result<T> {

        private RequestTask requestTask;
        private T response;

        private Result(RequestTask requestTask, T response) {
            this.requestTask = requestTask;
            this.response = response;
        }

    }


}

可拓展的響應處理callback,自己可根據(jù)需要拓展

public interface AbsCallback<T> {
    void sucess(T response);
    void failure(Exception e);
    T handleData(ByteArrayOutputStream response) throws HttpException;
}
public abstract class JsonCallback<T> implements AbsCallback<T> {

    private static Gson gson = new Gson();

    @Override
    @SuppressWarnings("unchecked")
    public T handleData(ByteArrayOutputStream response) throws HttpException {
        try {
            Class<T> clz= (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
            return gson.fromJson(response.toString("UTF-8"),clz);
        } catch (UnsupportedEncodingException e) {
            throw new HttpException(HttpException.Status.XXX_EXCEPTION);
        }
    }

}
public abstract class StringCallback implements AbsCallback<String> {

    @Override
    public String handleData(ByteArrayOutputStream response) throws HttpException {
        try {
            return response.toString("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new HttpException(HttpException.Status.XXX_EXCEPTION);
        }
    }
}

有問題猾愿,請留言交流

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末庵寞,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子简十,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,496評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件砸彬,死亡現(xiàn)場離奇詭異,居然都是意外死亡斯入,警方通過查閱死者的電腦和手機砂碉,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,407評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來刻两,“玉大人增蹭,你說我怎么就攤上這事∧治保” “怎么了沪铭?”我有些...
    開封第一講書人閱讀 162,632評論 0 353
  • 文/不壞的土叔 我叫張陵壮池,是天一觀的道長偏瓤。 經常有香客問我杀怠,道長,這世上最難降的妖魔是什么厅克? 我笑而不...
    開封第一講書人閱讀 58,180評論 1 292
  • 正文 為了忘掉前任赔退,我火速辦了婚禮,結果婚禮上证舟,老公的妹妹穿的比我還像新娘硕旗。我一直安慰自己,他們只是感情好女责,可當我...
    茶點故事閱讀 67,198評論 6 388
  • 文/花漫 我一把揭開白布漆枚。 她就那樣靜靜地躺著,像睡著了一般抵知。 火紅的嫁衣襯著肌膚如雪墙基。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,165評論 1 299
  • 那天刷喜,我揣著相機與錄音残制,去河邊找鬼。 笑死掖疮,一個胖子當著我的面吹牛初茶,可吹牛的內容都是我干的。 我是一名探鬼主播浊闪,決...
    沈念sama閱讀 40,052評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼恼布,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了搁宾?” 一聲冷哼從身側響起桥氏,我...
    開封第一講書人閱讀 38,910評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎猛铅,沒想到半個月后字支,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經...
    沈念sama閱讀 45,324評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡奸忽,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,542評論 2 332
  • 正文 我和宋清朗相戀三年堕伪,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片栗菜。...
    茶點故事閱讀 39,711評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡欠雌,死狀恐怖,靈堂內的尸體忽然破棺而出疙筹,到底是詐尸還是另有隱情富俄,我是刑警寧澤北戏,帶...
    沈念sama閱讀 35,424評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站无午,受9級特大地震影響瘪松,放射性物質發(fā)生泄漏。R本人自食惡果不足惜悠瞬,卻給世界環(huán)境...
    茶點故事閱讀 41,017評論 3 326
  • 文/蒙蒙 一们豌、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧浅妆,春花似錦望迎、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,668評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至康辑,卻和暖如春摄欲,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背晾捏。 一陣腳步聲響...
    開封第一講書人閱讀 32,823評論 1 269
  • 我被黑心中介騙來泰國打工蒿涎, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人惦辛。 一個月前我還...
    沈念sama閱讀 47,722評論 2 368
  • 正文 我出身青樓劳秋,卻偏偏與公主長得像,于是被迫代替她去往敵國和親胖齐。 傳聞我的和親對象是個殘疾皇子玻淑,可洞房花燭夜當晚...
    茶點故事閱讀 44,611評論 2 353

推薦閱讀更多精彩內容