okio okhttp

  Okio庫是由square公司開發的,補充了java.io和java.nio的不足,更加方便,快速的訪問、存儲和處理你的數據。而OkHttp的底層也使用該庫做爲支持。能夠讓你的i/o操做更加的簡單.java

Buffer類是方便訪問和存儲數據;有read和write方法git

Okio類是庫提供的一個供外部使用的類,提供了大量的靜態方法:github

其中有兩個十分重要的接口Sink 和 Sourceapi

Sink:就至關於OutputStream  寫操做  經過Sink能夠得到一個BufferedSink服務器

Source:就至關於InputStream  寫操做  經過Source能夠得到一個BufferedSourcemarkdown

簡單使用app

讀取複製文件異步

 try {
            //獲取BufferedSource
            BufferedSource source = Okio.buffer(Okio.source(new FileInputStream("in.txt")));
            //獲取BufferedSink
            BufferedSink sink = Okio.buffer((Okio.sink(new FileOutputStream("out.txt"))));
            //將source所有讀寫到sink中
            source.readAll(sink);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

  Okio工具類—ByteString類,這個類能夠用來作各類變化,它將byte轉會爲String,而這個String能夠是utf8的值,也能夠是base64後的值,也能夠是md5的值,也能夠是sha256的值,總之就是各類變化,最後取得你想要的值。ide

String str = "this is new string";
        ByteString string = ByteString.encodeUtf8(str);
        //打印string的base64值
        Log.e(TAG, "onCreate: " + string.base64() );
        //打印string的md5值
        Log.e(TAG, "onCreate: " + string.md5().hex() );

E/MainActivity: onCreate: dGhpcyBpcyBuZXcgc3RyaW5n
E/MainActivity: onCreate: [hex=9c5e308d65c718bc69d616a0b530b004]工具

 

OKHttp

 經常使用類:Request  同步提交請求和異步提交請求

    Response:響應  包括響應頭(Header) 響應碼(code) 響應體(content)

從服務器同步獲取數據

 private void get() {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.submit(new Runnable() {
            @Override
            public void run() {
                //獲取構建器
                Request.Builder builder = new Request.Builder();
                //添加url地址
                builder.url("https://raw.githubusercontent.com/square/okhttp/master/README.md");
                //獲取Request對象
                Request request = builder.build();
                Log.d(TAG, "run: " + request);
                //獲取Call對象
                Call call = mClient.newCall(request);
                try {
                    //提交同步請求
                    Response response = call.execute();
                    if (response.isSuccessful()) {
                        final String string = response.body().string();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mContentTextView.setText(string);
                            }
                        });
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        executor.shutdown();
    }

從服務器異步獲取數據

 private void response() {
        Request.Builder builder = new Request.Builder();
        builder.url("https://raw.githubusercontent.com/square/okhttp/master/README.md");
        Request request = builder.build();
        Call call = mClient.newCall(request);
        //提交異步請求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure() called with: call = [" + call + "], e = [" + e + "]");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, "onResponse() called with: call = [" + call + "], response = [" + response + "]");
                //獲取響應碼
                int code = response.code();
                //獲取響應頭 以map形式存在,能夠經過key值獲取對應的value
                Headers headers = response.headers();
                //獲取響應體
                String content = response.body().string();
                final StringBuilder buf = new StringBuilder();
                buf.append("code: " + code);
                buf.append("\nHeaders: \n" + headers);
                buf.append("\nbody: \n" + content);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mContentTextView.setText(buf.toString());
                    }
                });
            }
        });
    }

向服務器提交數據

 private void post() {
        //從服務器開發者文檔獲取MediaType
        MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");
        String POST_URL = "https://api.github.com/markdown/raw";
        Request.Builder builder = new Request.Builder();
        builder.url(POST_URL);
        builder.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, "Hello world github/linguist#1 **cool**, and #1!"));
        Request request = builder.build();
        Call call = mClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    final String content = response.body().string();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mContentTextView.setText(content);
                        }
                    });
                }
            }
        });
    }
相關文章
相關標籤/搜索