欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2024-03-05 17:35:43
http post 和 put 请求可以包含要提交的内容。只需要在创建 request 对象时,通过 post 和 put 方法来指定要提交的内容即可。 http pos...

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