1.定义post endpoint
2.通过payload java对象定义post body以及headers,传递给 HttpEntity()
? EvPlannerPayload ?requestPayload
request = new HttpEntity<>(requestPayload, headers);
3.call RestTemplate 对象exchange 方法,分别传递4个参数,传递url,http 请求方法,HttpEntity对象,响应对象
responseEntity = restTemplate.exchange(url, HttpMethod.POST, request, EvPlanner.class);
4.最后返回ResponseEntity<Object> 对象给测试用例使用
? ? ?
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
@Service
public class EvPlannerService {
public static String internalErrorMessage;
public static EvPlannerPayload requestPayload;
private ResponseEntity<EvPlanner> query(String url, String httpMethod) {
HttpHeaders headers = new HttpHeaders();
if (!"".equals($(EvPlannerPayload.class).getConfigGroup())) {
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("configGroup", $(EvPlannerPayload.class).getConfigGroup());
headers.set("region", $(EvPlannerPayload.class).getRegion().toUpperCase());
}
RestTemplate restTemplate = $(RestTemplate.class);
HttpEntity request = null;
ResponseEntity<EvPlanner> responseEntity = new ResponseEntity<EvPlanner>(new EvPlanner(), HttpStatus.OK);
try {
if (httpMethod.equals("get")) {
responseEntity = restTemplate.exchange(url, HttpMethod.GET, request, EvPlanner.class);
} else if (httpMethod.equals("post")) {
request = new HttpEntity<>(requestPayload, headers);
responseEntity = restTemplate.exchange(url, HttpMethod.POST, request, EvPlanner.class);
}
} catch (HttpServerErrorException exception) {
internalErrorMessage = exception.getMessage();
responseEntity = new ResponseEntity<EvPlanner>(new EvPlanner(), exception.getStatusCode());
responseEntity.getBody().setMessage(exception.getMessage());
}
if (!responseEntity.getStatusCode().is2xxSuccessful()) {
throw new RestClientException(responseEntity.getBody().getMessage());
}
return responseEntity;
}
// @Step("Step: call ev charging planner api by origin:{request.origin} destination:{request.destination} departure_battery_pct:{request.departure_battery_pct} preferred_arrival_battery_pct:{request.preferred_arrival_battery_pct} preferred_start_charge_battery_pct:{request.preferred_start_charge_battery_pct} preferred_stop_charge_battery_pct:{request.preferred_stop_charge_battery_pct")
public ResponseEntity<EvPlanner> getChargingPlans(EvPlannerPayload request) {
String url = null;
try {
url = $(GenerateURL.class).generateEvPlannerGetEndpoint(request);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return query(url, "get");
}
public ResponseEntity<EvPlanner> postChargingPlans(EvPlannerPayload request) {
String url = null;
try {
url = $(GenerateURL.class).generateEvPlannerEndpoint(request);
requestPayload = request;
} catch (Exception e) {
e.printStackTrace();
}
return query(url, "post");
}
}
|