1、基础的POST
@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));
}
2、POST 验证
如果想要验证请求,可以使用Credentials.basic构造器将凭证添加到header中
@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));
}
3. POST带json参数
为了在请求正文中发送 JSON,需要设置媒体类型为application/json。可以使用RequestBody.create builder来完成:
@Test
public void whenPostJson_thenCorrect() throws IOException {
String json = "{\"id\":1,\"name\":\"John\"}";
RequestBody body = RequestBody.create(
MediaType.parse("application/json"), json);
//MediaType.parse("application/json; charset=utf-16"), 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));
}
4、Multipart POST 请求
需要将RequestBody构建为MultipartBody用于post 例子中的file、username和password:
@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("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));
}