gpt4 book ai didi

java - 将 RestAssured 转换为 RestTemplate

转载 作者:行者123 更新时间:2023-11-30 02:37:18 28 4
gpt4 key购买 nike

有人可以帮我将下面的代码重构为 Spring RestTemplate 吗? postLogin 是稍后在 junit e2e 测试中使用的方法。

public class LoginLogoutAPI {

private static final LoginLogoutAPI INSTANCE = new LoginLogoutAPI();
private static final String LOGIN_ENDPOINT = "/auth/login";

public static LoginLogoutAPI getInstance() {
return INSTANCE;
}

public ValidatableResponse postLogin(String login, String password) {
return given()
.contentType(JSON)
.body(getCustomerCredentialsJson(login, password))
.when()
.post(LOGIN_ENDPOINT)
.then()
.statusCode(SC_OK);
}

private Map<String, String> getCustomerCredentialsJson(String login, String password) {
Map<String, String> customer = new LinkedHashMap<>();
customer.put("login", login);
customer.put("password", password);
return customer;
}
}

最佳答案

假设您的所有内容都正确,我将实现 Rest Template Exchange方法进行发布调用并捕获 ValidatableResponse 中的响应.

public class LoginLogoutAPI {

private static final LoginLogoutAPI INSTANCE = new LoginLogoutAPI();
private static final String LOGIN_ENDPOINT = "/auth/login";

public static LoginLogoutAPI getInstance() {
return INSTANCE;
}

public ValidatableResponse postLogin(String login, String password) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<byte[]> httpEntity = new HttpEntity<byte[]>(headers);
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(LOGIN_ENDPOINT)
.queryParam("login",login)
.queryParam("password",password);
URI uri=builder.buildAndExpand().toUri();
ResponseEntity<ValidatableResponse> rs = restTemplate.exchange(uri, HttpMethod.POST, httpEntity,ValidatableResponse.class);
return rs.getBody();
}
}

这是一个实现,但不是一个工作示例,因为我没有工作区设置。您必须更换您的 LOGIN_ENDPOINT以及其余模板的完整 URL。

如果您需要澄清,请告诉我!

关于java - 将 RestAssured 转换为 RestTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42716689/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com