android okhttp打印请求头_详解Android中使用OkHttp发送HTTP的post请求的方法

本文详细介绍了在Android中如何使用OkHttp库发送HTTP POST请求,包括提交字符串、流、文件、表单以及分块请求的方法,并给出了相关示例代码。
摘要由CSDN通过智能技术生成

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

标签相同效果的请求体。键值对将使用一种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());

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值