您当前的位置: 首页 >  http

梁云亮

暂无认证

  • 2浏览

    0关注

    1211博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

SpringBoot下 OkHttp3单元测试 之 Post

梁云亮 发布时间:2020-11-23 18:12:02 ,浏览量:2

示例:普通请求 服务器端代码
@PostMapping(value = "/login")
public Result userLogin(String username, String password, HttpServletResponse response) {
     //.......
}
测试代码
@Test
void login() throws IOException {
    OkHttpClient client = new OkHttpClient().newBuilder()
            .build();
    FormBody.Builder formBodyBuilder = new FormBody.Builder();
    formBodyBuilder.add("username", "zhangsan");
    formBodyBuilder.add("password", "1234");

    Request request = new Request.Builder()
            .url(baseUrl + "login")
            .post(formBodyBuilder.build())
            .addHeader("Content-Type", "application/json")
            .build();
    Response response = client.newCall(request).execute();

    System.out.println(response.body().string());
}
示例:提交Json String 服务器端代码
  • UserLoginDto.java
@Data
public class UserLoginDto implements Serializable {
    @NotBlank(message = "昵称不能为空")
    private String username;

    @NotBlank(message = "密码不能为空")
    private String password;
}
  • UserController.java
@PostMapping(value = "/login")
public Result userLogin(@RequestBody @Valid UserLoginDto userLoginDto, HttpServletResponse response) {
     //.......
}
测试代码
@Test
void login0() throws IOException {
    OkHttpClient client = new OkHttpClient().newBuilder().build();
    MediaType mediaType = MediaType.parse("application/json");
    RequestBody body = RequestBody.Companion.create("{\"username\":\"zhangsan\",\"password\":\"1234\"}", mediaType);

    Request request = new Request.Builder()
            .url(baseUrl + "login")
            .method("POST", body)
            .addHeader("Content-Type", "application/json")
            .build();
    Response response = client.newCall(request).execute();

    System.out.println(response.body().string());
}
关注
打赏
1665409997
查看更多评论
立即登录/注册

微信扫码登录

0.0432s