手寫Android網路框架——CatHttp(二)

panhaos發表於2018-01-23

前言

上一篇文章已經對http協議和整體框架做了一個大致的介紹: 手寫Android網路框架——CatHttp(一)

這篇文章我們主要就分析下具體子類是如何實現,以什麼方式構建成可以被伺服器識別並接受的資料型別提交上去的。所以這篇文章我們主要討論正文的資料型別和格式。

這裡寫圖片描述

Http正文

並不是每種請求方式都能攜帶正文,如post和put可以攜帶正文,而get和delete不能攜帶正文,有引數的話直接拼接在url後面。而不同的正文型別對應的一個請求頭(Content-Type)是不同的,Http協議根據這個請求頭按照對應的型別去解析正文。

正文型別

表單

如果正文傳入的是表單,那麼請求頭宣告的ContentType為:

application/x-www-form-urlencoded; charset=UTF-8

表單組織的結構格式為:

username=zhangsan&pwd=12345&date=2015

也就是當兩者均滿足該要求時,伺服器可以正常解析表單裡的資料。

檔案/二進位制

在最初的 http 協議中,沒有上傳檔案方面的功能。 rfc1867為 http 協議新增了這個功能。

如果想傳輸檔案或者一組二進位制位元組,則請求頭宣告的Content-Type宣告為:

"multipart/from-data; boundary=" + boundary;

其中boundary是一個隨機數,在下面的正文格式中會使用該boundary作為標識:

--AaB03x
Content-Disposition: form-data; name="field1"

Joe Blow
--AaB03x
Content-Disposition: form-data; name="pics"; filename="file1.txt"
Content-Type: text/plain

 ... contents of file1.txt ...
--AaB03x--
複製程式碼

可以看到,其實Multipart的方式也同時支援傳輸鍵值對,只是構造的方式不一樣,每一個(部分) ,姑且稱為部分,都是以--boundary開始的,並且後面跟著類似請求頭的鍵值對,用來說明資料型別,每部分的資料正文跟這種“請求頭”分隔開。

瞭解了不同正文的格式,我們就可以實現我們的子類了。

這裡寫圖片描述

針對於檔案這種格式會比較複雜,但是觀察會有一個共同點,也就是我們說的“部分”,這裡用Part表示,下面先看具體的http任務是怎麼執行的

Http任務的執行

HttpCall

可以看到,實際的Call實際不管是同步還是非同步,都是呼叫了HttpThreadPool提供的結構來執行Task,從而排程任務的執行的。

public class HttpCall implements Call {

    final Request request;

    final CatHttpClient.Config config;

    private IRequestHandler requestHandler = new RequestHandler();


    public HttpCall(CatHttpClient.Config config, Request request) {
        this.config = config;
        this.request = request;
    }


    @Override
    public Response execute() {
        Callable<Response> task = new SyncTask();
        Response response;
        try {
            response = HttpThreadPool.getInstance().submit(task);
            return response;
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new Response.Builder()
                .code(400)
                .message("執行緒異常中斷")
                .body(new ResponseBody(null))
                .build();
    }

    @Override
    public void enqueue(Callback callback) {
        Runnable runnable = new HttpTask(this, callback, requestHandler);
        HttpThreadPool.getInstance().execute(new FutureTask<>(runnable, null));
    }

    /**
     * 同步提交Callable
     */
    class SyncTask implements Callable<Response> {
        @Override
        public Response call() throws Exception {
            Response response = requestHandler.handlerRequest(HttpCall.this);
            return response;
        }
    }
}
複製程式碼

RequestHandler

RequestHandler 是網路請求的處理者,將請求的Request解析成標準的Http格式的請求提交給伺服器並獲取伺服器返回的內容。

public class RequestHandler implements IRequestHandler {

    @Override
    public Response handlerRequest(HttpCall call) throws IOException {

        HttpURLConnection connection = mangeConfig(call);

        if (!call.request.heads.isEmpty()) addHeaders(connection, call.request);

        if (call.request.body != null) writeContent(connection, call.request.body);

        if (!connection.getDoOutput()) connection.connect();

        //解析返回內容
        int responseCode = connection.getResponseCode();
        if (responseCode >= 200 && responseCode < 400) {
            byte[] bytes = new byte[1024];
            int len;
            InputStream ins = connection.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            while ((len = ins.read(bytes)) != -1) {
                baos.write(bytes, 0, len);
            }
            Response response = new Response
                    .Builder()
                    .code(responseCode)
                    .message(connection.getResponseMessage())
                    .body(new ResponseBody(baos.toByteArray()))
                    .build();
            try {
                ins.close();
                connection.disconnect();
            } finally {
                if (ins != null) ins.close();
                if (connection != null) connection.disconnect();
            }
            return response;
        }
        throw new IOException(String.valueOf(connection.getResponseCode()));
    }

    /**
     * 用
     *
     * @param connection
     * @param body
     * @throws IOException
     */
    private void writeContent(HttpURLConnection connection, RequestBody body) throws IOException {
        OutputStream ous = connection.getOutputStream();
        body.writeTo(ous);
    }

    /**
     * HttpUrlConnection基本引數的配置
     *
     * @param call
     * @return
     * @throws IOException
     */
    private HttpURLConnection mangeConfig(HttpCall call) throws IOException {
        URL url = new URL(call.request.url);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(call.config.connTimeout);
        connection.setReadTimeout(call.config.readTimeout);
        connection.setDoInput(true);
        if (call.request.body != null && Request.HttpMethod.checkNeedBody(call.request.method)) {
            connection.setDoOutput(true);
        }
        return connection;
    }

    /**
     * 給物件新增請求頭
     *
     * @param connection
     * @param request
     */
    private void addHeaders(HttpURLConnection connection, Request request) {
        Set<String> keys = request.heads.keySet();
        for (String key : keys) {
            connection.addRequestProperty(key, request.heads.get(key));
        }
    }
}
複製程式碼

工具類Util

public class Util {

    public static void checkMap(String key, String value) {
        if (key == null) throw new NullPointerException("key == null");
        if (key.isEmpty()) throw new NullPointerException("key is empty");
        if (value == null) throw new NullPointerException("value == null");
        if (value.isEmpty()) throw new NullPointerException("value is empty");
    }

    public static void checkMethod(Request.HttpMethod method, RequestBody body) {
        if (method == null)
            throw new NullPointerException("method == null");
        if (body != null && Request.HttpMethod.checkNoBody(method))
            throw new IllegalStateException("方法" + method + "不能有請求體");
        if (body == null && Request.HttpMethod.checkNeedBody(method))
            throw new IllegalStateException("方法" + method + "必須有請求體");
    }


    /**
     * 轉換成file的頭
     *
     * @param key
     * @param fileName
     * @return
     */
    public static String trans2FileHead(String key, String fileName) {
        StringBuilder sb = new StringBuilder();
        sb.append(MultipartBody.disposition)
                .append("name=")//name=

                .append("\"").append(key).append("\"").append(";").append(" ")//"key";

                .append("filename=")//filename

                .append("\"").append(fileName).append("\"")//"filename"

                .append("\r\n");

        return sb.toString();
    }

    /**
     * 轉換成表單形式
     *
     * @param key
     * @return
     */
    public static String trans2FormHead(String key) {
        StringBuilder sb = new StringBuilder();
        sb.append(MultipartBody.disposition)
                .append("name=")//name=

                .append("\"").append(key).append("\"") //"key"

                .append("\r\n");//next line

        return sb.toString();
    }

    public static byte[] getUTF8Bytes(String str) throws UnsupportedEncodingException {
        return str.getBytes("UTF-8");
    }


}

複製程式碼

RequestBody正文

FormBody

既然表單這種格式比較簡單,我們就先構建表單,可以看到,我們可以通過建造者的方式可以直接傳入鍵值對或者map,內部用一個ArrayMap來儲存鍵值對,寫出的時候將map裡的鍵值對按照表單的方式構建好再寫出去。

public class FormBody extends RequestBody {

    // 限制引數不要過多(ArrayMap效率,而且很少需要破k的引數)
    public static final int MAX_FROM = 1000;

    final Map<String, String> map;

    public FormBody(Builder builder) {
        this.map = builder.map;
    }

    @Override
    public String contentType() {
        return "application/x-www-form-urlencoded; charset=UTF-8";
    }

    @Override
    public void writeTo(OutputStream ous) throws IOException {
        try {
            ous.write(transToString(map).getBytes("UTF-8"));
            ous.flush();
        } finally {
            if (ous != null) {
                ous.close();
            }
        }
    }

    /**
     * 拼接請求引數
     *
     * @param map
     * @return
     */
    private String transToString(Map<String, String> map) throws UnsupportedEncodingException {
        StringBuilder sb = new StringBuilder();
        Set<String> keys = map.keySet();
        for (String key : keys) {
            if (!TextUtils.isEmpty(sb)) {
                sb.append("&");
            }
            sb.append(URLEncoder.encode(key, "UTF-8"));
            sb.append("=");
            sb.append(URLEncoder.encode(map.get(key), "UTF-8"));
        }
        return sb.toString();
    }


    public static class Builder {
        private Map<String, String> map;

        public Builder() {
            map = new ArrayMap<>();
        }

        public Builder add(String key, String value) {
            if (map.size() > MAX_FROM) throw new IndexOutOfBoundsException(" 請求引數過多");
            Util.checkMap(key, value);
            map.put(key, value);
            return this;
        }

        public Builder map(Map<String, String> map) {
            if (map.size() > MAX_FROM) throw new IndexOutOfBoundsException(" 請求引數過多");
            this.map = map;
            return this;
        }

        public FormBody build() {
            return new FormBody(this);
        }

    }
}

複製程式碼

Part

Part作為一個抽象類提供了兩個靜態方法用來建立不同的物件,一種是鍵值對,另一種是檔案。其中寫出正文的方法按照標準格式來就行了。

public abstract class Part {

    private Part() {
    }

    public abstract String contentType();

    public abstract String heads();

    public abstract void write(OutputStream ous) throws IOException;


    /**
     * 建立構建form的part
     *
     * @param key
     * @param value
     * @return
     */
    public static Part create(final String key, final String value) {

        return new Part() {
            @Override
            public String contentType() {
                return null;
            }

            @Override
            public String heads() {
                return Util.trans2FormHead(key);
            }

            @Override
            public void write(OutputStream ous) throws IOException {
                ous.write(heads().getBytes("UTF-8"));
                ous.write(END_LINE);
                ous.write(value.getBytes("UTF-8"));
                ous.write(END_LINE);
            }
        };
    }


    public static Part create(final String type, final String key, final File file) {
        if (file == null) throw new NullPointerException("file 為空");
        if (!file.exists()) throw new IllegalStateException("file 不存在");

        return new Part() {
            @Override
            public String contentType() {
                return type;
            }

            @Override
            public String heads() {
                return Util.trans2FileHead(key, file.getName());
            }

            @Override
            public void write(OutputStream ous) throws IOException {
                ous.write(heads().getBytes());
                ous.write("Content-Type: ".getBytes());
                ous.write(Util.getUTF8Bytes(contentType()));
                ous.write(END_LINE);
                ous.write(END_LINE);
                writeFile(ous, file);
                ous.write(END_LINE);
                ous.flush();
            }

            /**
             * 寫出檔案
             * @param ous&emsp;輸出流
             * @param file&emsp;檔案
             */
            private void writeFile(OutputStream ous, File file) throws IOException {
                FileInputStream ins = null;
                try {
                    ins = new FileInputStream(file);
                    int len;
                    byte[] bytes = new byte[2048];
                    while ((len = ins.read(bytes)) != -1) {
                        ous.write(bytes, 0, len);
                    }
                } finally {
                    if (ins != null) {
                        ins.close();
                    }
                }
            }
        };

    }
}
複製程式碼

MultipartBody

MultipartBody 儲存了一組Part物件,對外提供了兩個介面——傳入鍵值對和傳入檔案,同時按照上面Multipart的格式寫出body儲存的所有內容。

public class MultipartBody extends RequestBody {

    public static final String disposition = "content-disposition: form-data; ";
    public static final byte[] END_LINE = {'\r', '\n'};
    public static final byte[] PREFIX = {'-', '-'};

    final List<Part> parts;
    final String boundary;

    public MultipartBody(Builder builder) {
        this.parts = builder.parts;
        this.boundary = builder.boundary;
    }

    @Override
    public String contentType() {
        return "multipart/from-data; boundary=" + boundary;
    }

    @Override
    public void writeTo(OutputStream ous) throws IOException {
        try {
            for (Part part : parts) {
                ous.write(PREFIX);
                ous.write(boundary.getBytes("UTF-8"));
                ous.write(END_LINE);
                part.write(ous);
            }
            ous.write(PREFIX);
            ous.write(boundary.getBytes("UTF-8"));
            ous.write(PREFIX);
            ous.write(END_LINE);
            ous.flush();
        } finally {
            if (ous != null) {
                ous.close();
            }
        }
    }

    public static class Builder {

        private String boundary;
        private List<Part> parts;

        public Builder() {
            this(UUID.randomUUID().toString());
        }

        private Builder(String boundary) {
            this.parts = new ArrayList<>();
            this.boundary = boundary;
        }

        public Builder addPart(String type, String key, File file) {
            if (key == null) throw new NullPointerException("part name == null");
            parts.add(Part.create(type, key, file));
            return this;
        }

        public Builder addForm(String key, String value) {
            if (key == null) throw new NullPointerException("part name == null");
            parts.add(Part.create(key, value));
            return this;
        }

        public MultipartBody build() {
            if (parts.isEmpty()) throw new NullPointerException("part list == null");
            return new MultipartBody(this);
        }
    }
}
複製程式碼

結語

具體實現類基本如上,這兩篇就是CatHttp的全部內容了,原始碼已經放在github上——傳送門,如果有什麼不足之處,歡迎大家指正,如果覺得我寫的還不錯,就關注我吧~

這裡寫圖片描述

相關文章