編輯:關於 Android 程式設計
HTTP POST 與 PUT 請求可以攜帶要提交的內容。在 OkHttp 中,只需在建立 Request 物件時透過 post() 或 put() 指定內容即可。本文依「字串、串流、檔案、表單、多部件」五種情境,示範各自的寫法。
public class PostString {
public static void main(String[] args) throws IOException {
OkHttpClient client = new OkHttpClient();
MediaType MEDIA_TYPE_TEXT = MediaType.parse("text/plain");
String postBody = "Hello World";
Request request = new Request.Builder()
.url("https://www.baidu.com")
.post(RequestBody.create(MEDIA_TYPE_TEXT, postBody))
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException("服務器端錯誤: " + response);
}
System.out.println(response.body().string());
}
}
以 String 提交只適用於內容較小的情況。當請求內容龐大時,應改用串流方式,避免一次性把整份資料載入記憶體。
請求體的內容由串流寫入產生。以下範例直接寫入 Okio 的 BufferedSink;若你的程式使用 OutputStream,可透過 BufferedSink.outputStream() 取得。
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 {
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());
}
把檔案作為請求體非常簡單,RequestBody.create 直接接受 File 物件:
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());
}
使用 FormEncodingBuilder 可建構出與 HTML <form> 相同效果的請求體,鍵值對會以 HTML 相容的 URL 編碼方式處理:
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());
}
MultipartBuilder 可建構複雜的請求體,與 HTML 的檔案上傳格式相容。多部件請求體中每一部分都是獨立的請求體,可定義自己的標頭;這些標頭用來描述該部分內容,例如它的 Content-Disposition。若 Content-Length 與 Content-Type 可用,會被自動加入標頭。
private static final String IMGUR_CLIENT_ID = "...";
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
// 使用 imgur 的圖片上傳 API
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addPart(
Headers.of("Content-Disposition", "form-data; name=\"title\""),
RequestBody.create(null, "Square Logo"))
.addPart(
Headers.of("Content-Disposition", "form-data; name=\"image\""),
RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
.build();
Request request = new Request.Builder()
.header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
.url("https://api.imgur.com/3/image")
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
本文範例基於 OkHttp 3.x 的 API 寫法。在 OkHttp 4.x 中,由於改用 Kotlin 撰寫,部分 Builder 類別(如 FormEncodingBuilder、MultipartBuilder)已被 FormBody.Builder 與 MultipartBody.Builder 取代,RequestBody.create 的參數順序也有所調整。若使用新版,請以對應的 Builder 寫法為準。此外,記得在執行網路請求前於 AndroidManifest.xml 加上 android.permission.INTERNET 權限,並避免在主執行緒執行同步請求。
Android 7.0 PowerManagerService 解析(三):updatePowerStateLocked 的五個階段
前面我們已經理清了兩條主線:進程要用電時向 PMS 申請 WakeLock,用完之後釋放。而無論是申請還是釋放,PMS 的最終動作都是同一個——呼叫 updatePowe
Android ViewPager Tab 切換實戰:滑動與下標指示器同步
ViewPager 的橫向滑動切換是極高頻的需求。本文實作一個帶標題與滑動指示圖的三頁 Tab 結構,讓手勢滑動與點擊切換都能帶動底部指示器平滑移動。 一、MainA
兩行程式碼搞定 Android 視圖擴散切換動畫
用最精簡的接入方式,為 Android 視圖切換加上擴散式的過場動畫。 一、概述 這兩天動手做了一個視圖擴散切換效果的控制器,API 相容到 Android 4.0,讓畫
Android 縮圖載入優化:以 inSampleSize 與 createScaledBitmap 節省記憶體
為何要載入縮圖 在列表或資訊流中,通常不需要載入原圖,只要顯示縮圖即可。這樣可以明顯降低記憶體使用,避免大圖造成崩潰。 載入流程 可先使用 inJustDecodeB