当前位置:   article > 正文

okhttp3 post请求_okhttp3 post json

okhttp3 post json

1、基础的POST

  1. @Test
  2. public void whenSendPostRequest_thenCorrect()
  3. throws IOException {
  4. RequestBody formBody = new FormBody.Builder()
  5. .add("username", "test")
  6. .add("password", "test")
  7. .build();
  8. Request request = new Request.Builder()
  9. .url(BASE_URL + "/users")
  10. .post(formBody)
  11. .build();
  12. Call call = client.newCall(request);
  13. Response response = call.execute();
  14. assertThat(response.code(), equalTo(200));
  15. }

2、POST 验证

如果想要验证请求,可以使用Credentials.basic构造器将凭证添加到header中

  1. @Test
  2. public void whenSendPostRequestWithAuthorization_thenCorrect()
  3. throws IOException {
  4. String postBody = "test post";
  5. Request request = new Request.Builder()
  6. .url(URL_SECURED_BY_BASIC_AUTHENTICATION)
  7. .addHeader("Authorization", Credentials.basic("username", "password"))
  8. .post(RequestBody.create(
  9. MediaType.parse("text/x-markdown), postBody))
  10. .build();
  11. Call call = client.newCall(request);
  12. Response response = call.execute();
  13. assertThat(response.code(), equalTo(200));
  14. }

3. POST带json参数

为了在请求正文中发送 JSON,需要设置媒体类型为application/json。可以使用RequestBody.create builder来完成:

  1. @Test
  2. public void whenPostJson_thenCorrect() throws IOException {
  3. String json = "{\"id\":1,\"name\":\"John\"}";
  4. RequestBody body = RequestBody.create(
  5. MediaType.parse("application/json"), json);
  6. //MediaType.parse("application/json; charset=utf-16"), json);
  7. Request request = new Request.Builder()
  8. .url(BASE_URL + "/users/detail")
  9. .post(body)
  10. .build();
  11. Call call = client.newCall(request);
  12. Response response = call.execute();
  13. assertThat(response.code(), equalTo(200));
  14. }

4、Multipart POST 请求

需要将RequestBody构建为MultipartBody用于post 例子中的file、username和password:

  1. @Test
  2. public void whenSendMultipartRequest_thenCorrect()
  3. throws IOException {
  4. RequestBody requestBody = new MultipartBody.Builder()
  5. .setType(MultipartBody.FORM)
  6. .addFormDataPart("username", "test")
  7. .addFormDataPart("password", "test")
  8. .addFormDataPart("file", "file.txt",
  9. RequestBody.create(MediaType.parse("application/octet-stream"),
  10. new File("test/resources/test.txt")))
  11. .build();
  12. Request request = new Request.Builder()
  13. .url(BASE_URL + "/users/multipart")
  14. .post(requestBody)
  15. .build();
  16. Call call = client.newCall(request);
  17. Response response = call.execute();
  18. assertThat(response.code(), equalTo(200));
  19. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/441120
推荐阅读
相关标签
  

闽ICP备14008679号