有人可以帮我修改下面的代码到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;
}
}
答案 0 :(得分:2)
假设您已将此处的所有内容更正确,我将实施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
替换为其余模板的完整网址。
如果您需要澄清,请告诉我!