溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

一、OkHttp請求方法

發(fā)布時間:2020-07-16 19:21:23 來源:網(wǎng)絡(luò) 閱讀:1953 作者:xiaofei_zhang 欄目:移動開發(fā)

OkHttp是一個高效的HTTP庫:


  1. 支持 SPDY ,共享同一個 Socket 來處理同一個服務(wù)器的所有請求

  2. 如果 SPDY 不可用,則通過連接池來減少請求延時

  3. 無縫的支持GZIP來減少數(shù)據(jù)流量

  4. 緩存響應(yīng)數(shù)據(jù)來減少重復(fù)的網(wǎng)絡(luò)請求


  OkHttp 處理了很多網(wǎng)絡(luò)疑難雜癥:會從很多常用的連接問題中自動恢復(fù)。如果您的服務(wù)器配置了多個IP地址,當(dāng)?shù)谝粋€IP連接失敗的時候,OkHttp會自動嘗試下一個IP。OkHttp還處理了代理服務(wù)器問題和SSL握手失敗問題。


  OkHttp是一個相對成熟的解決方案,據(jù)說Android4.4的源碼中可以看到HttpURLConnection已經(jīng)替換成OkHttp實現(xiàn)了。所以我們更有理由相信OkHttp的強(qiáng)大。


1、HTTP請求方法

  • 同步GET請求

private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
    Request request = new Request.Builder()
            .url("http://publicobject.com/helloworld.txt")
            .build();
    Response response = client.newCall(request).execute();
    if (!response.isSuccessful())
        throw new IOException("Unexpected code " + response);
    Headers responseHeaders = response.headers();
    for (int i = 0; i < responseHeaders.size(); i++) {
        System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
    }
    System.out.println(response.body().string());
}

  Response類的string()方法會把文檔的所有內(nèi)容加載到內(nèi)存,適用于小文檔,對應(yīng)大于1M的文檔,應(yīng)   使用流()的方式獲取。

response.body().byteStream()
  • 異步GET請求

private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
    Request request = new Request.Builder()
            .url("http://publicobject.com/helloworld.txt")
            .build();
    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            e.printStackTrace();
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            Headers responseHeaders = response.headers();
            for (int i = 0; i < responseHeaders.size(); i++) {
                System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
            }

            System.out.println(response.body().string());
        }
    });
}

  讀取響應(yīng)會阻塞當(dāng)前線程,所以發(fā)起請求是在主線程,回調(diào)的內(nèi)容在非主線程中。

  • POST方式提交字符串

private static final MediaType MEDIA_TYPE_MARKDOWN
        = MediaType.parse("text/x-markdown; charset=utf-8");

private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
    String postBody = ""
            + "Releases\n"
            + "--------\n"
            + "\n"
            + " * _1.0_ May 6, 2013\n"
            + " * _1.1_ June 15, 2013\n"
            + " * _1.2_ August 11, 2013\n";

    Request request = new Request.Builder()
            .url("https://api.github.com/markdown/raw")
            .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))
            .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) 
        throw new IOException("Unexpected code " + response);

    System.out.println(response.body().string());
}

  因為整個請求體都在內(nèi)存中,應(yīng)避免提交1M以上的文件。

  • POST方式提交流

private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
    RequestBody requestBody = new RequestBody() {
        @Override
        public MediaType contentType() {
            return MEDIA_TYPE_MARKDOWN;
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            sink.writeUtf8("Numbers\n");
            sink.writeUtf8("-------\n");
            for (int i = 2; i <= 997; i++) {
                sink.writeUtf8(String.format(" * %s = %s\n", i, factor(i)));
            }
        }

        private String factor(int n) {
            for (int i = 2; i < n; i++) {
                int x = n / i;
                if (x * i == n) return factor(x) + " × " + i;
            }
            return Integer.toString(n);
        }
    };

    Request request = new Request.Builder()
            .url("https://api.github.com/markdown/raw")
            .post(requestBody)
            .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) 
        throw new IOException("Unexpected code " + response);

    System.out.println(response.body().string());
}

  使用Okio框架以流的形式將內(nèi)容寫入,這種方式不會出現(xiàn)內(nèi)存溢出問題。

  • POST方式提交文件

public static final MediaType MEDIA_TYPE_MARKDOWN
        = MediaType.parse("text/x-markdown; charset=utf-8");

private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
    File file = new File("README.md");

    Request request = new Request.Builder()
            .url("https://api.github.com/markdown/raw")
            .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
            .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) 
        throw new IOException("Unexpected code " + response);

    System.out.println(response.body().string());
}
  • POST方式提交表單

private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
    RequestBody formBody = new FormEncodingBuilder()
            .add("search", "Jurassic Park")
            .build();
    Request request = new Request.Builder()
            .url("https://en.wikipedia.org/w/index.php")
            .post(formBody)
            .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) 
        throw new IOException("Unexpected code " + response);

    System.out.println(response.body().string());
}

  表單的每個Names-Values都進(jìn)行了URL編碼。如果服務(wù)器端接口未進(jìn)行URL編碼,可定制個  FormBuilder。

  • 文件上傳(兼容html文件上傳)

private static final String IMGUR_CLIENT_ID = "...";
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("p_w_picpath/png");

private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
    // Use the imgur p_w_picpath upload API as documented at https://cache.yisu.com/upload/information/20200311/46/200136.jpg")))
            .build();

    Request request = new Request.Builder()
            .header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
            .url("https://api.imgur.com/3/p_w_picpath")
            .post(requestBody)
            .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) 
        throw new IOException("Unexpected code " + response);
    System.out.println(response.body().string());
}


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI