詳解Android中使用OkHttp發(fā)送HTTP的post請(qǐng)求的方法
HTTP POST 和 PUT 請(qǐng)求可以包含要提交的內(nèi)容。只需要在創(chuàng)建 Request 對(duì)象時(shí),通過(guò) post 和 put 方法來(lái)指定要提交的內(nèi)容即可。
HTTP POST 請(qǐng)求的基本示例:
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("http://www.baidu.com")
.post(RequestBody.create(MEDIA_TYPE_TEXT, postBody))
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException("服務(wù)器端錯(cuò)誤: " + response);
}
System.out.println(response.body().string());
}
}
以 String 類型提交內(nèi)容只適用于內(nèi)容比較小的情況。當(dāng)請(qǐng)求內(nèi)容較大時(shí),應(yīng)該使用流來(lái)提交。
Post方式提交流
以流的方式POST提交請(qǐng)求體。請(qǐng)求體的內(nèi)容由流寫入產(chǎn)生。這個(gè)例子是流直接寫入 Okio 的BufferedSink。你的程序可能會(huì)使用 OutputStream ,你可以使用 BufferedSink.outputStream() 來(lái)獲取。
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());
}
Post方式提交文件
以文件作為請(qǐng)求體是十分簡(jiǎn)單的。
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方式提交表單
使用 FormEncodingBuilder 來(lái)構(gòu)建和HTML <form> 標(biāo)簽相同效果的請(qǐng)求體。鍵值對(duì)將使用一種HTML兼容形式的URL編碼來(lái)進(jìn)行編碼。
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());
}
Post方式提交分塊請(qǐng)求
MultipartBuilder 可以構(gòu)建復(fù)雜的請(qǐng)求體,與HTML文件上傳形式兼容。多塊請(qǐng)求體中每塊請(qǐng)求都是一個(gè)請(qǐng)求體,可以定義自己的請(qǐng)求頭。這些請(qǐng)求頭可以用來(lái)描述這塊請(qǐng)求,例如他的 Content-Disposition 。如果 Content-Length 和 Content-Type 可用的話,他們會(huì)被自動(dòng)添加到請(qǐng)求頭中。
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 {
// Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image
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());
}
相關(guān)文章
簡(jiǎn)單說(shuō)說(shuō)Android中如何使用攝像頭和相冊(cè)
本篇文章主要介紹了簡(jiǎn)單說(shuō)說(shuō)Android中如何使用攝像頭和相冊(cè),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-05-05
Android開(kāi)發(fā)之TabHost選項(xiàng)卡及相關(guān)疑難解決方法
這篇文章主要介紹了Android開(kāi)發(fā)之TabHost選項(xiàng)卡及相關(guān)疑難解決方法,結(jié)合實(shí)例形式較為詳細(xì)的分析了Android開(kāi)發(fā)中TabHost選項(xiàng)卡的常見(jiàn)用法以及相關(guān)疑難問(wèn)題解決方法,需要的朋友可以參考下2019-03-03
Android中設(shè)置只有程序第一次運(yùn)行才顯示的界面實(shí)現(xiàn)思路
如何實(shí)現(xiàn)程序第一次運(yùn)行才顯示的界面,下面是具體的實(shí)現(xiàn)思路及步驟,有類似需求的朋友可以參考下哈2013-06-06
Android編程之退出整個(gè)應(yīng)用程序的方法
這篇文章主要介紹了Android編程之退出整個(gè)應(yīng)用程序的方法,實(shí)例分析了Android直接關(guān)閉所有的Acitivity并退出應(yīng)用程序的實(shí)現(xiàn)技巧,需要的朋友可以參考下2015-12-12
Android使用google breakpad捕獲分析native cash
這篇文章主要介紹了Android使用google breakpad捕獲分析native cash 的相關(guān)知識(shí),非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-04-04
完美解決Android App啟動(dòng)頁(yè)有白屏閃過(guò)的問(wèn)題
這篇文章主要介紹了完美解決Android App啟動(dòng)頁(yè)有白屏閃過(guò)的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-08-08

