详解Android中使用OkHttp发送HTTP的post请求的方法

HTTP POST 和 PUT 请求可以包含要提交的内容。只需要在创建 Request 对象时,通过 post 和 put 方法来指定要提交的内容即可。HTTP POST 请求的基本示例:

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("服务器端错误: " + response);  }  System.out.println(response.body().string());  }}

以 String 类型提交内容只适用于内容比较小的情况。当请求内容较大时,应该使用流来提交。

Post方式提交流

以流的方式POST提交请求体。请求体的内容由流写入产生。这个例子是流直接写入 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());}

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方式提交表单

使用 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());}

Post方式提交分块请求

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 { // 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());}

如果心在远方,只需勇敢前行,梦想自会引路,

详解Android中使用OkHttp发送HTTP的post请求的方法

相关文章:

你感兴趣的文章:

标签云: