OkHttp是一個高效的HTTP庫:
創(chuàng)新互聯(lián)是一家專注網(wǎng)站建設(shè)、網(wǎng)絡(luò)營銷策劃、小程序設(shè)計、電子商務(wù)建設(shè)、網(wǎng)絡(luò)推廣、移動互聯(lián)開發(fā)、研究、服務(wù)為一體的技術(shù)型公司。公司成立10年以來,已經(jīng)為上1000家成都玻璃貼膜各業(yè)的企業(yè)公司提供互聯(lián)網(wǎng)服務(wù)?,F(xiàn)在,服務(wù)的上1000家客戶與我們一路同行,見證我們的成長;未來,我們一起分享成功的喜悅。
支持 SPDY ,共享同一個 Socket 來處理同一個服務(wù)器的所有請求
如果 SPDY 不可用,則通過連接池來減少請求延時
無縫的支持GZIP來減少數(shù)據(jù)流量
緩存響應數(shù)據(jù)來減少重復的網(wǎng)絡(luò)請求
OkHttp 處理了很多網(wǎng)絡(luò)疑難雜癥:會從很多常用的連接問題中自動恢復。如果您的服務(wù)器配置了多個IP地址,當?shù)谝粋€IP連接失敗的時候,OkHttp會自動嘗試下一個IP。OkHttp還處理了代理服務(wù)器問題和SSL握手失敗問題。
OkHttp是一個相對成熟的解決方案,據(jù)說Android4.4的源碼中可以看到HttpURLConnection已經(jīng)替換成OkHttp實現(xiàn)了。所以我們更有理由相信OkHttp的強大。
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)存,適用于小文檔,對應大于1M的文檔,應 使用流()的方式獲取。
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()); } }); }
讀取響應會阻塞當前線程,所以發(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)存中,應避免提交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都進行了URL編碼。如果服務(wù)器端接口未進行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 /upload/otherpic57/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()); }
網(wǎng)站標題:一、OkHttp請求方法
文章出自:http://www.rwnh.cn/article8/ghcjip.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供標簽優(yōu)化、域名注冊、品牌網(wǎng)站制作、定制網(wǎng)站、ChatGPT、云服務(wù)器
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)