I am using RestTemplate in my project to make a post request to an endpoint. Basically I have lambda function written in nestjs. I am injecting lambda service in my java project. If vehicleName if condition
passes, I would like to POST that vehicleName to the url
. Is there any suggestions on how I can achieve this? I would be testing my application using this command
curl -X POST "https://gdxdispatcher.dev.awstrp.net/dispatcher/service/api/message" -H "accept: */*" -H "Content-Type: application/json" -d "{\"vehicleType\":\"US Mutual Fund,VIP\",\"source\":\"PCS_DATACACHE_TOPIC\"}"
Here is my code
private void callLambdaService(String vehicleTypesParamValue)
{
final String url = "http://localhost:3000/dispatcher/service/api/message";
final String zMETHOD = "callLambdaService - ";
RestTemplate restTemplate = new RestTemplate();
restTemplate.exchange("url", HttpMethod.POST, vehicleName, String.class);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
String result = restTemplate.getForObject(url, String.class);
VehicleType vehicleName=null;
String[] vehicleTypes = vehicleTypesParamValue.split(",");
Set<VehicleType> results = new HashSet<>();
try
{
for (String vehicleTypeParam : vehicleTypes)
{
vehicleName =
vehicleTypeFactory.getVehicleTypeByIspName(
vehicleTypeParam);
if (vehicleName == null)
{
LOGGER.warn("No codes for products or vehicle types were supplied");
}
else if (vehicleName.equals("US Mutual Fund"))
{
LOGGER.info(zMETHOD + "Vehicles provided: "
+ vehicleName.getIspName());
}
else
{
LOGGER.warn(
String.format("Unknown vehicle type provided: [%s]",
vehicleName.getIspName()));
}
}
}catch (Exception e) {
LOG.error("Unable to get vehicletype data", e);
}
}
Well, following the instructions:
Create headers which will be a data structure representing HTTP request.
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
Build a JSONObject from org.json
package that is a modifiable set of name/value mappings and put names and values.
JSONObject requestBody = new JSONObject();
requestBody.put("vehicleType", "US Mutual Fund,VIP");
requestBody.put("source", "PCS_DATACACHE_TOPIC");
Create our HttpEntity that represents an HTTP request or response, in this case request consisting of headers and body.
HttpEntity<String> request = new HttpEntity<>(requestBody.toString(), headers);
Create a new resource by posting an object to the given URI
template.
It returns the result as automatically converted to the type specified in the responseType parameter.
Then we define a ObjectNode
as our resource and response type as our result.
ObjectNode result = restTemplate.postForObject("https://gdxdispatcher.dev.awstrp.net/dispatcher/service/api/message",
request, ObjectNode.class);