I want to call another spring boot on spring boot
I read a lot of articles
Spring RestTemplate GET with parameters
Spring RestTemplate
Many more...
Temporary methods that I can currently use
final String uri = "http://127.0.0.1:8888/key";
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(uri)
.queryParam("id", "1234")
.queryParam("model", "model")
.queryParam("name", "name")
.queryParam("description", "description")
.queryParam("status", 0)
.queryParam("mode", 1)
.queryParam("creationDate", "2021/05/24 12:34:56")
.queryParam("updatedDate", "2021/05/24 12:34:56");
HttpEntity<?> entity = new HttpEntity<>(headers);
HttpEntity<String> response = restTemplate.exchange(
builder.toUriString(),
HttpMethod.PUT,
entity,
String.class);
I want to be able to use the class directly instead of slowly entering all the parameters
public class DataDto {
private String id;
private String model;
private String name;
private String description;
private int status;
private int mode;
private String creationDate;
private String updatedDate;
...
}
How can I use the entire class as a parameter at once?
I have tried many similar things, but there are no parameters on my server:
logger.info("getId:" + dataDto.getId());
final String uri = "http://127.0.0.1:8888/key";
RestTemplate restTemplate = new RestTemplate();
restTemplate.put(uri, DataDto.class, dataDto);
Try something like below.
Override toString() method for DataDto
#Override
public String toString() {
return String.format("id=%s&" +
"model=%s&" +
"name=%s&" +
"description=%s&" +
"status=%s&" +
"mode=%s&" +
"creationDate=%s&" +
"updatedDate=%s", id, model, name, description, status, mode,
creationDate, updatedDate);
}
Formulate URL like below,
final String uri = String.format("%s?%s", "http://127.0.0.1:8888/key", dataDto.toString())
Related
I need to send a value from an Angularjs front to a springboot Java back-office.
The back is called by many other fronts and services.
Which means I can change The front but I have to make sure that any change on the back must not break it for the other callers.
So Extra headers or Other fields in the request body etc... any change that won't break the other existing calls is what I'm looking for.
An example of some methods signature:
A HTTP GET signature
#Override
#ResponseStatus(code = HttpStatus.OK)
#RequestMapping(value = "/", method = RequestMethod.GET)
public ResponseEntity<List<Something>> getSomething(
#RequestHeader(name = Constants.HEADER.SOME_CODE) final String code,
#RequestHeader(name = Constants.HEADER.COMPANY_ID) final String companyId,
#RequestHeader(name = Constants.HEADER.CLIENT_ID) final String clientId) {
A HTTP POST signature
#Override
#ResponseStatus(code = HttpStatus.OK)
#RequestMapping(value = "/{pathValue}/transactions", method = RequestMethod.POST)
public ResponseEntity<SomeResponse> requestSomething(
#RequestHeader(name = Constants.HEADER.EFS_CODE) final String vode,
#RequestHeader(name = Constants.HEADER.COMPANY_ID) final String companyId,
#RequestHeader(name = "Access-Code", required = false) final String codeAcces,
#RequestHeader(name = Constants.HEADER.CLIENT_ID) final String clientId,
#PathVariable("pathValue") final String pathValue,
#RequestBody #Valid Transact transaction) {
I'm new to Spring and I'm having trouble consuming an API and serialising the Response to Java POJOs using Jackson. This the API endpoint I'm trying to consume.
This what my request looks like:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.set("Authorization", "Bearer " + applicationProperties.getApiKey());
ArrayList<String> externalIds = new ArrayList<>();
externalIds.add(userId);
Map<String, Object> parameters = new HashMap<>();
parameters.put("external_ids", externalIds);
HttpEntity<Map<String, Object>> request = new HttpEntity<>(parameters, headers);
ResponseEntity<ProfileExportDTO> response = this.restTemplate.postForEntity(url, request , ProfileExportDTO.class);
This is my POJO class (setters and getters removed for simplicity):
#JsonIgnoreProperties(ignoreUnknown = true)
public class ProfileExportDTO implements Serializable {
#JsonProperty("first_name")
private String firstname;
#JsonProperty("last_name")
private String lastname;
private String language;
private String email;
private String dob;
#JsonProperty("home_city")
private String city;
private String country;
private String phone;
#JsonProperty("time_zone")
private String timezone;
#JsonProperty("last_coordinates")
private float[] lastCoordinates;
private String gender;
#JsonProperty("total_revenue")
private float revenue;
private String attributed_campaign;
private String attributed_source;
private String attributed_adgroup;
private String push_subscribe;
private String email_subscribe;
My problem is that when this runs the produced object is null. Does anyone know why?
I have model:
public class StudyModel {
#Id
private String ID;
private boolean isStable;
private String LastUpdate;
private MainTest test;
public static class MainTest {
private String test1;
private String test2;
}
}
I want to parse it to my model.
It works correctly but when it goes to MainTest where on json file I have couple values it fails and I have null on the rest of fields.
How I can deal with it?
public StudyModel getStudyDetails(String studyId){
RestTemplate restTemplate = new RestTemplate();
String url = URL + "studies/" + studyId;
ResponseEntity<String> serverResponse = restTemplate.getForEntity(url, String.class);
Gson g = new Gson();
String json = serverResponse.getBody();
StudyModel study = g.fromJson(json, StudyModel.class);
return study;
}
RestTemplate can handle deserialization for you
ResponseEntity<StudyModel> serverResponse = restTemplate.getForEntity(url, StudyModel.class);
StudyModel studyModel = serverResponse.getBody();
I am trying to map this Json response I consume through a secured RESTful API; however, the mapping is for some reason not happening correctly as I keep getting a NULL response instead of populated object.
This is my entity:
#JsonTypeName("order")
#JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT ,use = JsonTypeInfo.Id.NAME)
public class Order {
#JsonProperty("id")
private long customerd;
#JsonProperty("email")
private String customeEmail;
public long getCustomerd() {
return customerd;
}
public void setCustomerd(long customerd) {
this.customerd = customerd;
}
public String getCustomeEmail() {
return customeEmail;
}
public void setCustomeEmail(String customeEmail) {
this.customeEmail = customeEmail;
}
}
This is my service method:
public Order orderDetails (#RequestBody Order order){
String username = "username";
String password = "password";
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth(username, password);
// request url
String url = "https://test.myshopify.com/admin/orders/2013413015655.json";
RestTemplate restTemplate = new RestTemplate();
HttpEntity request = new HttpEntity(headers);
ResponseEntity<Order> response = restTemplate.exchange(
url, HttpMethod.GET, request, Order.class);
return order;
}
This is my Controller Method:
#GetMapping("/orderdetails")
#ResponseStatus(HttpStatus.FOUND)
public Order getBasicAut(Order order){
return basicAuth.orderDetails(order);
}
You should configure your REST to produce the JSON content
#GetMapping(path = "/orderdetails", produces = {MediaType.APPLICATION_JSON_VALUE})
Specifically, those codes below work well
#RestController
public class JsonController {
#GetMapping(path = "/orderdetails", produces = {MediaType.APPLICATION_JSON_VALUE})
#ResponseStatus(HttpStatus.FOUND)
public Order sendJsonBack() {
final Order order = new Order();
order.setCustomerd(123L);
order.setCustomeEmail("mail#gmail.com");
return order;
}
}
#Data
class Order implements Serializable {
private static final long serialVersionUID = -4258392267221190600L;
#JsonProperty("id")
private long customerd;
#JsonProperty("email")
private String customeEmail;
}
The issue was with what my methods were returning. They both have to return a ResponseEntity of type Order as in:
public ResponseEntity<Order> orderDetails (#RequestBody Order order){
String username = "username";
String password = "password";
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth(username, password);
// request url
String url = "https://test.myshopify.com/admin/orders/2013413015655.json";
RestTemplate restTemplate = new RestTemplate();
HttpEntity request = new HttpEntity(headers);
ResponseEntity<Order> response = restTemplate.exchange(
url, HttpMethod.GET, request, Order.class);
return response;
}
And my Controller to:
#GetMapping("/orderdetails")
#ResponseStatus(HttpStatus.FOUND)
public ResponseEntity<Order> getBasicAut(Order order){
return basicAuth.orderDetails(order);
}
I have two classes:
public class Person {
private String Name;
private Integer Age;
private String Surname;
// getters and setters
}
public class Animal {
private String Name;
private Integer Age;
// getters and setters
}
And the thing I wanna do - post Animal.class and receive response in Person.class format. (On the client side).
For this purpose I'm using REST Template:
RestTemplate restTemplate = new RestTemplate();
Person result = restTemplate.postForObject("http://url.com", HttpMethod.POST, Animal.class, Person.class);
I know that passing Animal.class this way is not right, but I cannot set Name and Age parameters manually in this page. The main requirement to use POST method.
So what I have to do to make it work?
I believe what you are looking for is:
RestTemplate restTemplate = new RestTemplate();
HttpEntity<Animal> request = new HttpEntity<>(animal); //populated object
ResponseEntity<Person> response = restTemplate.
exchange(url, HttpMethod.POST, request, Person.class);