前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用OkHttp发送POST请求的快速入门指南

使用OkHttp发送POST请求的快速入门指南

作者头像
明明如月学长
发布2021-08-31 11:18:29
8.5K0
发布2021-08-31 11:18:29
举报
文章被收录于专栏:明明如月的技术专栏

1介绍

本文将介绍 OkHttp 客户端的基本用法。

在本篇简短的技术文章中,我们将特别介绍 OkHttp 3.x 版本中发送Post请求的不同方式。

2 基本的 POST 请求

我们可以使用 FormBody.Builder 构造基本的 RequestBody , 包含两个参数:用户名、密码,发送 POST请求。

代码语言:javascript
复制
@Test
public void whenSendPostRequest_thenCorrect() 
  throws IOException {
    RequestBody formBody = new FormBody.Builder()
      .add("username", "test")
      .add("password", "test")
      .build();
 
    Request request = new Request.Builder()
      .url(BASE_URL + "/users")
      .post(formBody)
      .build();
 
    Call call = client.newCall(request);
    Response response = call.execute();
     
    assertThat(response.code(), equalTo(200));

3 带授权的 POST 请求

如果要对请求进行身份验证,可以使用 Credentials.basic 构建器向请求头中添加凭据。

下面代码给出发送一个 String 字符串作为请求体带授权的例子:

代码语言:javascript
复制
@Test
public void whenSendPostRequestWithAuthorization_thenCorrect() 
  throws IOException {
    String postBody = "test post";
     
    Request request = new Request.Builder()
      .url(URL_SECURED_BY_BASIC_AUTHENTICATION)
      .addHeader("Authorization", Credentials.basic("username", "password"))
      .post(RequestBody.create(
        MediaType.parse("text/x-markdown), postBody))
      .build();
 
    Call call = client.newCall(request);
    Response response = call.execute();
 
    assertThat(response.code(), equalTo(200));
}

4 POST方式发送 JSON 数据

为了在请求体中发送 JSON,我们必须设置它的媒体类型 application/json。 我们可以使用 RequestBody.create构建器来构造:

代码语言:javascript
复制
@Test
public void whenPostJson_thenCorrect() throws IOException {
    String json = "{\"id\":1,\"name\":\"John\"}";
 
    RequestBody body = RequestBody.create(
      MediaType.parse("application/json"), json);
 
    Request request = new Request.Builder()
      .url(BASE_URL + "/users/detail")
      .post(body)
      .build();
  
    Call call = client.newCall(request);
    Response response = call.execute();
 
    assertThat(response.code(), equalTo(200));
}

5 Multipart POST 请求

为了发送一个 Multipart Post 请求, 我们需要将 RequestBody 构建为一个 MultipartBody 来发布文件、用户名和密码的 POST 请求:

代码语言:javascript
复制
@Test
public void whenSendMultipartRequest_thenCorrect() 
  throws IOException {  
    RequestBody requestBody = new MultipartBody.Builder()
      .setType(MultipartBody.FORM)
      .addFormDataPart("username", "test")
      .addFormDataPart("password", "test")
      .addFormDataPart("file", "file.txt",
        RequestBody.create(MediaType.parse("application/octet-stream"), 
          new File("src/test/resources/test.txt")))
      .build();
 
    Request request = new Request.Builder()
      .url(BASE_URL + "/users/multipart")
      .post(requestBody)
      .build();
 
    Call call = client.newCall(request);
    Response response = call.execute();
 
    assertThat(response.code(), equalTo(200));
}

6 发送不带默认字符编码的POST 请求

Okhttp 的默认字符编码是 UTF-8:

代码语言:javascript
复制
@Test
public void whenPostJsonWithoutCharset_thenCharsetIsUtf8() throws IOException {
    final String json = "{\"id\":1,\"name\":\"John\"}";
 
    final RequestBody body = RequestBody.create(
        MediaType.parse("application/json"), json);
 
    String charset = body.contentType().charset().displayName();
 
    assertThat(charset, equalTo("UTF-8"));
}

如果我们想使用其他字符编码,我们可以将其作为 MediaType.parse () 的第二个参数传入:

代码语言:javascript
复制
@Test
public void whenPostJsonWithUtf16Charset_thenCharsetIsUtf16() throws IOException {
    final String json = "{\"id\":1,\"name\":\"John\"}";
 
    final RequestBody body = RequestBody.create(
        MediaType.parse("application/json; charset=utf-16"), json);
 
    String charset = body.contentType().charset().displayName();
 
    assertThat(charset, equalTo("UTF-16"));
}

7 总结

在这篇短文中,我们给出了几个使用 OkHttp 客户端发送 POST 请求的示例。

和往常一样,本文的示例代码已发布在 GitHub上。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/01/01 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1介绍
  • 2 基本的 POST 请求
  • 3 带授权的 POST 请求
  • 4 POST方式发送 JSON 数据
  • 5 Multipart POST 请求
  • 6 发送不带默认字符编码的POST 请求
  • 7 总结
相关产品与服务
多因子身份认证
多因子身份认证(Multi-factor Authentication Service,MFAS)的目的是建立一个多层次的防御体系,通过结合两种或三种认证因子(基于记忆的/基于持有物的/基于生物特征的认证因子)验证访问者的身份,使系统或资源更加安全。攻击者即使破解单一因子(如口令、人脸),应用的安全依然可以得到保障。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档