okhttp3使用-基礎篇

前言

在很長一段時間裏,我一直使用HttpClient這個庫進行網絡請求的處理。這個庫的版本經歷了至關大的歷史變遷,並且每每存在諸多的BUG。php

咱們一塊兒來回顧下HttpClient的的歷史,HttpClient項目開始於2001年,它是做爲 Jakarta Commons的一個子項目。雖然該項目在2005年被HttpComponents項目所取代,也就是開始了HttpClient 3.x時代。在2007年的時候HttpComponents成爲了Apache的頂級項目。並且該項目分裂成兩個模塊:HttpClient 和 HttpCore 。因此項目的維護者也是看到該庫的一些不足因此在不停的更替版本。這樣就致使一個問題,各類項目的版本混亂,並且其API也是不兼容,甚至存在使用可能會存在內存泄露的重大BUG版本。html

相信經過本系列文章,你也許會在新的項目中嘗試使用現代化的設計更爲簡潔的okhttp3進行網絡相關的開發。java

okhttp3概覽

首先貼上項目地址:square.github.io/okhttp/,若是對源碼感興趣能夠fork一份進行學習。該項目star有27k+,確實算是很多。主要仍是其對android的高可用性和socket複用,很是適合移動端的開發,可是對於web端的Java應用開發也是一樣的強大。android

其主要特性以下:git

  • 支持HTTP/2以及SPDY協議,容許全部同一個主機地址的請求共享同一個socket鏈接
  • 使用鏈接池能夠縮短請求延時
  • 自帶GZIP壓縮減小響應數據的大小
  • 緩存響應內容,避免一些徹底重複的請求

其核心主要有路由、鏈接協議、攔截器、代理、安全性認證、鏈接池以及網絡適配,攔截器主要是指添加,移除或者轉換請求或者回應的頭部信息,總流程圖以下:github


注:圖片來自網絡,侵權即刪web

這個流程主要是經過Diapatcher不斷從RequestQueue中取出請求(Call),根據是否已緩存從內存緩存或是服務器取得請求的數據,其具體實現細節之後再單獨撰文討論。spring

兼容性

  • Android 2.3+
  • Java1.7

若是你的項目還在使用Java1.6的話趕忙升級JDK吧。apache

基本使用

okhttp3支持同步和異步請求,若是不想堵塞調用線程咱們通常使用異步請求,在Callback中獲取請求返回結果再進一步處理。後端

請求操做通常都有一個套路:

構造OkHttpClient(能夠經過new或者Builder)->構造Request->newCall->Call#execute或者Call#enqueue。最後一步操做就是同步或者異步請求的區別。

發送GET請求

同步請求的實例代碼以下:

/** * 同步GET請求 * -OkHttpClient#Builder構造客戶端對象; * -構造Request對象; * -經過前兩步中的對象構建Call對象; * -經過Call#execute(Callback)方法來提交異步請求; */
@Test
public void syncGetCall() throws IOException {
    OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(5, TimeUnit.SECONDS).build();
    final Request request = new Request.Builder()
            .url(url)
            .get()//默認就是GET請求,能夠不寫
            .build();
    Call call = okHttpClient.newCall(request);
    Response response = call.execute();
    logger.debug(response.body().string());
}複製代碼

異步請求實例代碼以下:

/** * 異步GET請求 * -OkHttpClient#Builder構造客戶端對象; * -構造Request對象; * -經過前兩步中的對象構建Call對象; * -經過Call#enqueue(Callback)方法來提交異步請求; */
@Test
public void asyncGetCall() throws Exception{
    OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(5, TimeUnit.SECONDS).build();;
    final Request request = new Request.Builder()
            .url(url)
            .get()//默認就是GET請求,能夠不寫
            .build();
    Call call = okHttpClient.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            logger.error("onFailure: ");
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            logger.debug("onResponse: " + response.body().string());
        }
    });
    //等待請求線程,不然主線程結束沒法看到請求結果
    Thread.currentThread().join(5000);
}複製代碼

異步操做的時候主線程必需要調用join,不然請求還沒處理玩線程就退出看不到打印信息。

發送POST請求

post和get最大的區別局勢post請求須要構造一個RequestBody對象來填充須要發送的數據。咱們來看他的建立方法:


從create 方法簽名就能夠看出,它支持發送stirng,字節流和文件。下面對各類數據發送進行舉例。

提交String數據

/** * post發送String數據 * 這裏使用github的markdown編輯器API,咱們發送一個文本,編輯器會返回格式化富文本信息 */
@Test
public void postStringTest() throws InterruptedException {
    MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
    String requestBody = "hello github";
    Request request = new Request.Builder()
            .url("https://api.github.com/markdown/raw")
            .post(RequestBody.create(mediaType, requestBody))
            .build();
    OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            logger.debug("onFailure: " + e.getMessage());
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            logger.debug(response.protocol() + " " + response.code() + " " + response.message());
            Headers headers = response.headers();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < headers.size(); i++) {
                sb.append(headers.name(i) + ":" + headers.value(i)).append("\n");
            }
            logger.debug("headers:\n{}",sb.toString());
            logger.debug("onResponse: " + response.body().string());
        }
    });
    Thread.currentThread().join(5000);
}複製代碼

返回結果:

11:21:08.385 [OkHttp https://api.github.com/...] DEBUG OkHttpTest - http/1.1 200 OK
11:21:08.389 [OkHttp https://api.github.com/...] DEBUG OkHttpTest - headers:
Date:Tue, 10 Jul 2018 03:21:09 GMT
Content-Type:text/html;charset=utf-8
Transfer-Encoding:chunked
Server:GitHub.com
Status:200 OK
X-RateLimit-Limit:60
X-RateLimit-Remaining:52
X-RateLimit-Reset:1531194293
X-CommonMarker-Version:0.17.4
Access-Control-Expose-Headers:ETag, Link, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval
Access-Control-Allow-Origin:*
Strict-Transport-Security:max-age=31536000; includeSubdomains; preload
X-Frame-Options:deny
X-Content-Type-Options:nosniff
X-XSS-Protection:1; mode=block
Referrer-Policy:origin-when-cross-origin, strict-origin-when-cross-origin
Content-Security-Policy:default-src 'none'
X-Runtime-rack:0.022042
Vary:Accept-Encoding
X-GitHub-Request-Id:08AC:05AB:1776494:1F2723C:5B442624

11:21:08.392 [OkHttp https://api.github.com/...] DEBUG OkHttpTest - onResponse: <p>hello github</p>
複製代碼

最終返回了<p>hello github</p>,說明咱們的請求發送成功了。注意這裏是異步發送POST請求,一樣須要再主線程執行Thread.currentThread().join();

提交字節流

/** * 發送字節流 * 可使用create方法或者重載RequestBody進行自定義構造 * @throws InterruptedException * @throws UnsupportedEncodingException */
@Test
public void postBytesTest() throws InterruptedException, UnsupportedEncodingException {
    RequestBody requestBody = new RequestBody() {
        @Nullable
        @Override
        public MediaType contentType() {
            return MediaType.parse("text/x-markdown; charset=utf-8");
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            sink.writeUtf8("你好,github");
        }
    };
    //requestBody = RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), "你好,github".getBytes("utf-8"));
    Request request = new Request.Builder()
            .url("https://api.github.com/markdown/raw")
            .post(requestBody)
            .build();
    OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            logger.debug("onFailure: " + e.getMessage());
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            logger.debug(response.protocol() + " " + response.code() + " " + response.message());
            Headers headers = response.headers();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < headers.size(); i++) {
                sb.append(headers.name(i) + ":" + headers.value(i)).append("\n");
            }
            logger.debug("headers:\n{}", sb.toString());
            logger.debug("onResponse: " + response.body().string());
        }
    });
    Thread.currentThread().join(5000);
}複製代碼

返回結果:

11:32:52.421 [OkHttp https://api.github.com/...] DEBUG OkHttpTest - http/1.1 200 OK
11:32:52.424 [OkHttp https://api.github.com/...] DEBUG OkHttpTest - headers:
Date:Tue, 10 Jul 2018 03:32:54 GMT
Content-Type:text/html;charset=utf-8
Transfer-Encoding:chunked
Server:GitHub.com
Status:200 OK
X-RateLimit-Limit:60
X-RateLimit-Remaining:47
X-RateLimit-Reset:1531194293
X-CommonMarker-Version:0.17.4
Access-Control-Expose-Headers:ETag, Link, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval
Access-Control-Allow-Origin:*
Strict-Transport-Security:max-age=31536000; includeSubdomains; preload
X-Frame-Options:deny
X-Content-Type-Options:nosniff
X-XSS-Protection:1; mode=block
Referrer-Policy:origin-when-cross-origin, strict-origin-when-cross-origin
Content-Security-Policy:default-src 'none'
X-Runtime-rack:0.026395
Vary:Accept-Encoding
X-GitHub-Request-Id:0B55:5D3F:C0CE72:1032A20:5B4428E4

11:32:52.426 [OkHttp https://api.github.com/...] DEBUG OkHttpTest - onResponse: <p>你好,github</p>
複製代碼

注意,上邊RequestBody也能夠本身重載實現。

提交文件

/** * 發送文件 * @throws InterruptedException */
@Test
public void postFileTest() throws InterruptedException {
    MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
    OkHttpClient okHttpClient = new OkHttpClient();
    File file = new File("D:\\code\\work\\egovaCloud\\src\\test\\java\\test.md");
    Request request = new Request.Builder()
            .url("https://api.github.com/markdown/raw")
            .post(RequestBody.create(mediaType, file))
            .build();
    okHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            logger.debug("onFailure: " + e.getMessage());
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            logger.debug(response.protocol() + " " + response.code() + " " + response.message());
            Headers headers = response.headers();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < headers.size(); i++) {
                sb.append(headers.name(i) + ":" + headers.value(i)).append("\n");
            }
            logger.debug("headers:\n{}", sb.toString());
            logger.debug("onResponse: " + response.body().string());
        }
    });
    Thread.currentThread().join(5000);
}複製代碼

返回結果:

11:43:56.177 [OkHttp https://api.github.com/...] DEBUG OkHttpTest - http/1.1 200 OK
11:43:56.180 [OkHttp https://api.github.com/...] DEBUG OkHttpTest - headers:
Date:Tue, 10 Jul 2018 03:43:57 GMT
Content-Type:text/html;charset=utf-8
Transfer-Encoding:chunked
Server:GitHub.com
Status:200 OK
X-RateLimit-Limit:60
X-RateLimit-Remaining:43
X-RateLimit-Reset:1531194293
X-CommonMarker-Version:0.17.4
Access-Control-Expose-Headers:ETag, Link, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval
Access-Control-Allow-Origin:*
Strict-Transport-Security:max-age=31536000; includeSubdomains; preload
X-Frame-Options:deny
X-Content-Type-Options:nosniff
X-XSS-Protection:1; mode=block
Referrer-Policy:origin-when-cross-origin, strict-origin-when-cross-origin
Content-Security-Policy:default-src 'none'
X-Runtime-rack:0.025442
Vary:Accept-Encoding
X-GitHub-Request-Id:0E27:0259:C79992:108ADDE:5B442B7B

11:43:56.183 [OkHttp https://api.github.com/...] DEBUG OkHttpTest - onResponse: <h2>
<a id="user-content-hello-github" class="anchor" href="#hello-github" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>hello github</h2>提交表單複製代碼

提交表單

/** * post提交表單,使用FormBody來構造表單鍵值對 */
@Test
public void postFormDataTest() throws InterruptedException {
    OkHttpClient okHttpClient = new OkHttpClient();
    RequestBody requestBody = new FormBody.Builder()
            .add("search", "java")
            .build();
    Request request = new Request.Builder()
            .url("https://en.wikipedia.org/w/index.php")
            .post(requestBody)
            .build();

    okHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            logger.debug("onFailure: " + e.getMessage());
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            logger.debug(response.protocol() + " " + response.code() + " " + response.message());
            Headers headers = response.headers();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < headers.size(); i++) {
                sb.append(headers.name(i) + ":" + headers.value(i)).append("\n");
            }
            logger.debug("headers:\n{}", sb.toString());
            logger.debug("onResponse: " + 
response.body().string());
        }
    });
    Thread.currentThread().join(5000);
}複製代碼

這裏是向 wiki網站發起關鍵字搜索,由於返回結果太長不在此展現返回結果。

數據分塊傳輸

使用MutipartBody能夠進行分塊傳輸,每一個塊均可以自定義Header,好比咱們須要傳送一個圖片而且須要攜帶額外的信息,則能夠本身構建下面的請求:

/** * 上傳文件同時寫到額外表單參數 * @throws Exception */
@Test
public void postMutilPartFormData() throws Exception{
    MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    RequestBody requestBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("extra", "extra args")
            .addFormDataPart("file", "logo.png",
                    RequestBody.create(MEDIA_TYPE_PNG, new File("D:\\code\\work\\egovaCloud\\src\\main\\resources\\static\\image\\logo.png")))
            .build();
    Request request = new Request.Builder()
            .url("http://localhost:8888/base-platform/upload/uploadFile")
            .post(requestBody)
            .build();
    OkHttpClient client = new OkHttpClient();
    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

    logger.debug(response.body().string());
}複製代碼

addFormDataPart這個方法實際上是下面方法的縮寫:

.addPart(
         Headers.of("Content-Disposition", "form-data; name=\"extra\""),
         RequestBody.create(null, "Square Logo"))複製代碼

這樣咱們就不須要單獨去設置這個頭部信息。

在後端咱們使用spring的MultipartHttpServletRequest就能夠後去額外的參數,實例代碼以下:

package cn.com.egova.baseplatform.controller;

import cn.com.egova.baseplatform.enums.ResultCode;
import cn.com.egova.baseplatform.util.ResultUtils;
import io.swagger.annotations.Api;
import org.activiti.engine.impl.persistence.StrongUuidGenerator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

/**
 * 客戶端文件上傳
 * Created by gxf on 17-5-26.
 */
@Controller
@RequestMapping(value = "/upload")
@Api(tags = "文件上傳模塊")
public class FileUploadController {
    @Value("${app.upload-path}")
    private String uploadPath;

    /**
     * 客戶端文件上傳保存至指定目錄
     *
     * @param request
     * @param saveDirPrefix 文件保存路勁
     * @return
     */
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    @ResponseBody
    public Object uploadFile(HttpServletRequest request, String saveDirPrefix) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");
        String fileName = file.getOriginalFilename();
        fileName = new StrongUuidGenerator().getNextId() + fileName.substring(fileName.indexOf("."));
        //保存
        try {
            String filePath = uploadPath + saveDirPrefix;
            File fileDir = new File(filePath);
            if (!fileDir.exists())
                fileDir.mkdirs();
            File targetFile = new File(filePath, fileName);
            targetFile.deleteOnExit();
            file.transferTo(targetFile);
            //返回圖片下載地址
            return ResultUtils.success(saveDirPrefix + fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtils.error(ResultCode.APP_ICO_FAILED);
        }

    }
}複製代碼

使用MultipartHttpServletRequest能夠獲取文件流和相關參數。

文件上傳進度監控

咱們能夠將文件分紅多個塊進行分批次傳輸,主要是在RequestBody的writeTo方法中計算累計發送的文件字節數,具體實現以下:

/** * 文件上傳進度 */
@Test
public void fileuploadProgressMonitor() throws InterruptedException {
    RequestBody progressRequestBody = new RequestBody() {
        //一次發送2K數據
        private static final int SEGMENT_SIZE = 2 * 1024;
        private File file = new File("D:\\RequestBody.png");

        private ProgressListener listener = new ProgressListener() {
            @Override
            public void transferred(long size) throws IOException {
                BigDecimal decimalSize = new BigDecimal(size * 100);
                BigDecimal decimalLen = new BigDecimal(contentLength());
                logger.info("完成:{}%", decimalSize.divide(decimalLen, 2, RoundingMode.HALF_DOWN));
            }
        };

        @Override
        public MediaType contentType() {
            return null;
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            logger.info("開始上傳文件:{},文件大小:{} 字節", file.getCanonicalPath(), this.contentLength());
            Source source = null;
            try {
                //待發送文件轉換爲Source
                source = Okio.source(file);
                long total = 0;
                long read;
                while ((read = source.read(sink.buffer(), SEGMENT_SIZE)) != -1) {
                    total += read;
                    sink.flush();
                    this.listener.transferred(total);

                }
            } finally {
                Util.closeQuietly(source);
            }

        }

        @Override
        public long contentLength() throws IOException {
            return file.length();
        }
    };
    RequestBody requestBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("file", "test", progressRequestBody)
            .build();
    Request request = new Request.Builder()
            .url("http://localhost:8888/base-platform/upload/uploadFile")
            .post(requestBody)
            .build();
    OkHttpClient client = new OkHttpClient();
    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            logger.debug(response.toString());
        }
    });
    Thread.currentThread().join(5000);
}複製代碼

在writeTo方法中咱們實際上是使用了okio這個庫來進行文件讀讀寫操做,後面也會單獨介紹這個IO庫的使用。在while中每次發送了2K字節數據,而後把累加器的值傳遞給外部的監聽器,而後打印當前進度。

運行結果以下:

11:17:05.883 [OkHttp http://localhost:8888/...] INFO OkHttpTest - 開始上傳文件:D:\RequestBody.png,文件大小:6245 字節
11:17:05.897 [OkHttp http://localhost:8888/...] INFO OkHttpTest - 完成:32.79%
11:17:05.898 [OkHttp http://localhost:8888/...] INFO OkHttpTest - 完成:65.59%
11:17:05.901 [OkHttp http://localhost:8888/...] INFO OkHttpTest - 完成:98.38%
11:17:05.901 [OkHttp http://localhost:8888/...] INFO OkHttpTest - 完成:100.00%
11:17:05.948 [OkHttp http://localhost:8888/...] DEBUG OkHttpTest - Response{protocol=http/1.1, code=200, message=, url=http://localhost:8888/base-platform/upload/uploadFile}
複製代碼

the end

至此okhttp3的基礎使用都講完了,看完本篇文章應該對常見的場景都能應付自如了。後面有時間在介紹攔截器等高級主題。

最後附上整個測試代碼,注意最後的文件上傳後端處理僅供參考。

import com.sun.istack.internal.Nullable;
import okhttp3.*;
import okhttp3.internal.Util;
import okio.BufferedSink;
import okio.Okio;
import okio.Source;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.concurrent.TimeUnit;

/** * @auther gongxufan * @date 2018/7/9 **/
public class OkHttpTest {

    private static final Logger logger = LoggerFactory.getLogger(OkHttpTest.class);
    private static String url = "https://www.jianshu.com";

    /** * 同步GET請求 * -OkHttpClient#Builder構造客戶端對象; * -構造Request對象; * -經過前兩步中的對象構建Call對象; * -經過Call#execute(Callback)方法來提交異步請求; */
    @Test
    public void syncGetCall() throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(5, TimeUnit.SECONDS).build();
        final Request request = new Request.Builder()
                .url(url)
                .get()//默認就是GET請求,能夠不寫
                .build();
        Call call = okHttpClient.newCall(request);
        Response response = call.execute();
        logger.debug(response.body().string());
    }

    /** * 異步GET請求 * -OkHttpClient#Builder構造客戶端對象; * -構造Request對象; * -經過前兩步中的對象構建Call對象; * -經過Call#enqueue(Callback)方法來提交異步請求; */
    @Test
    public void asyncGetCall() throws Exception {
        OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(5, TimeUnit.SECONDS).build();
        ;
        final Request request = new Request.Builder()
                .url(url)
                .get()//默認就是GET請求,能夠不寫
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                logger.error("onFailure: ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                logger.debug("onResponse: " + response.body().string());
            }
        });
        //等待請求線程,不然主線程結束沒法看到請求結果
        Thread.currentThread().join();
    }

    /** * post發送String數據 * 這裏使用github的markdown編輯器API,咱們發送一個文本,編輯器會返回格式化富文本信息 */
    @Test
    public void postStringTest() throws InterruptedException {
        MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
        String requestBody = "hello github";
        Request request = new Request.Builder()
                .url("https://api.github.com/markdown/raw")
                .post(RequestBody.create(mediaType, requestBody))
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                logger.debug("onFailure: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                logger.debug(response.protocol() + " " + response.code() + " " + response.message());
                Headers headers = response.headers();
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < headers.size(); i++) {
                    sb.append(headers.name(i) + ":" + headers.value(i)).append("\n");
                }
                logger.debug("headers:\n{}", sb.toString());
                logger.debug("onResponse: " + response.body().string());
            }
        });
        Thread.currentThread().join();
    }

    /** * 發送字節流 * 可使用create方法或者重載RequestBody進行自定義構造 * * @throws InterruptedException * @throws UnsupportedEncodingException */
    @Test
    public void postBytesTest() throws InterruptedException, UnsupportedEncodingException {
        RequestBody requestBody = new RequestBody() {
            @Nullable
            @Override
            public MediaType contentType() {
                return MediaType.parse("text/x-markdown; charset=utf-8");
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                sink.writeUtf8("你好,github");
            }
        };
        //requestBody = RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), "你好,github".getBytes("utf-8"));
        Request request = new Request.Builder()
                .url("https://api.github.com/markdown/raw")
                .post(requestBody)
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                logger.debug("onFailure: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                logger.debug(response.protocol() + " " + response.code() + " " + response.message());
                Headers headers = response.headers();
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < headers.size(); i++) {
                    sb.append(headers.name(i) + ":" + headers.value(i)).append("\n");
                }
                logger.debug("headers:\n{}", sb.toString());
                logger.debug("onResponse: " + response.body().string());
            }
        });
        Thread.currentThread().join();
    }

    /** * 發送文件 * * @throws InterruptedException */
    @Test
    public void postFileTest() throws InterruptedException {
        MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
        OkHttpClient okHttpClient = new OkHttpClient();
        File file = new File("D:\\code\\work\\egovaCloud\\src\\test\\java\\test.md");
        Request request = new Request.Builder()
                .url("https://api.github.com/markdown/raw")
                .post(RequestBody.create(mediaType, file))
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                logger.debug("onFailure: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                logger.debug(response.protocol() + " " + response.code() + " " + response.message());
                Headers headers = response.headers();
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < headers.size(); i++) {
                    sb.append(headers.name(i) + ":" + headers.value(i)).append("\n");
                }
                logger.debug("headers:\n{}", sb.toString());
                logger.debug("onResponse: " + response.body().string());
            }
        });
        Thread.currentThread().join(5000);
    }

    /** * post提交表單,使用FormBody來構造表單鍵值對 */
    @Test
    public void postFormDataTest() throws InterruptedException {
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("search", "java")
                .build();
        Request request = new Request.Builder()
                .url("https://en.wikipedia.org/w/index.php")
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                logger.debug("onFailure: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                logger.debug(response.protocol() + " " + response.code() + " " + response.message());
                Headers headers = response.headers();
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < headers.size(); i++) {
                    sb.append(headers.name(i) + ":" + headers.value(i)).append("\n");
                }
                logger.debug("headers:\n{}", sb.toString());
                logger.debug("onResponse: " + response.body().string());
            }
        });
        Thread.currentThread().join(5000);
    }

    /** * 上傳文件同時寫到額外表單參數 * * @throws Exception */
    @Test
    public void postMutilPartFormData() throws Exception {
        MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("extra", "extra args")
                .addFormDataPart("file", "logo.png",
                        RequestBody.create(MEDIA_TYPE_PNG, new File("D:\\code\\work\\egovaCloud\\src\\main\\resources\\static\\image\\logo.png")))
                .build();
        Request request = new Request.Builder()
                .url("http://localhost:8888/base-platform/upload/uploadFile")
                .post(requestBody)
                .build();
        OkHttpClient client = new OkHttpClient();
        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

        logger.debug(response.body().string());
    }

    /** * 文件上傳進度 */
    @Test
    public void fileuploadProgressMonitor() throws InterruptedException {
        RequestBody progressRequestBody = new RequestBody() {
            //一次發送2K數據
            private static final int SEGMENT_SIZE = 2 * 1024;
            private File file = new File("D:\\RequestBody.png");

            private ProgressListener listener = new ProgressListener() {
                @Override
                public void transferred(long size) throws IOException {
                    BigDecimal decimalSize = new BigDecimal(size * 100);
                    BigDecimal decimalLen = new BigDecimal(contentLength());
                    logger.info("完成:{}%", decimalSize.divide(decimalLen, 2, RoundingMode.HALF_DOWN));
                }
            };

            @Override
            public MediaType contentType() {
                return null;
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                logger.info("開始上傳文件:{},文件大小:{} 字節", file.getCanonicalPath(), this.contentLength());
                Source source = null;
                try {
                    //待發送文件轉換爲Source
                    source = Okio.source(file);
                    long total = 0;
                    long read;
                    while ((read = source.read(sink.buffer(), SEGMENT_SIZE)) != -1) {
                        total += read;
                        sink.flush();
                        this.listener.transferred(total);

                    }
                } finally {
                    Util.closeQuietly(source);
                }

            }

            @Override
            public long contentLength() throws IOException {
                return file.length();
            }
        };
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", "test", progressRequestBody)
                .build();
        Request request = new Request.Builder()
                .url("http://localhost:8888/base-platform/upload/uploadFile")
                .post(requestBody)
                .build();
        OkHttpClient client = new OkHttpClient();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                logger.debug(response.toString());
            }
        });
        Thread.currentThread().join(5000);
    }

    public interface ProgressListener {
        void transferred(long size) throws IOException;
    }
}

複製代碼
相關文章
相關標籤/搜索