Restful Spring postForObject missing all property values - java

I try to simulate restful server:
private void btnPostActionPerformed(java.awt.event.ActionEvent evt) {
RestTemplate restTemplate = new RestTemplate();
Issuer issuer = new Issuer();
issuer.setCountry("Teacher 1");
issuer.setIssuerName("Department 1");
String url = txtHost.getText()+txtGet.getText();
restTemplate.postForObject(url, issuer, Issuer.class) ;
}
Controller code:
#RequestMapping(value = "/issuer/addIssuer", method = RequestMethod.POST)
#ResponseBody
public Issuer addIssuer(#ModelAttribute("issuer") Issuer issuer) {
if (issuer != null) {
logger.info("Inside addIssuer, adding: " + issuer.toString());
} else {
logger.info("Inside addIssuer...");
}
issuers.put(issuer.getTicker(), issuer);
return issuer;
}
I have fill some attributes, but when I debug the server, all values is null.
INFO : com.avaldes.tutorial.RestController - Inside addIssuer, adding: [null, null, null, null]
IssuerName and country is null too..
What is wrong with my code?

You are using #ModelAttribute in your controller. In that case you'll need to send your data as application/x-www-form-urlencoded:
MultiValueMap<String, Object> variables = new LinkedMultiValueMap<>();
variables.add("country", "Teacher 1");
variables.add("issuerName", "Department 1");
RestTemplate restTemplate = new RestTemplate();
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(variables, requestHeaders);
String url = txtHost.getText()+txtGet.getText();
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, Issuer.class);

Related

How to fetch data from http response entity?

I am using SpringBoot to fetch access Token from my client. I could not separate the Access Token from the responseEntity. Is there a way to Fetch the AccessToken data alone?
Here is the code:
public ResponseEntity generate_Access_token() {
String url = "https://zoom.us/oauth/token";
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
final Gson gson = new Gson();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("grant_type", "account_credentials");
map.add("client_id", "XXX");
map.add("client_secret", "XXX");
map.add("account_id", "XXX");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );
//ResponseEntity<String> response_data=new ResponseEntity<String>(response.toString(), HttpStatus.CREATED);
ResponseEntity<AccessTokenResponse> response_data = restTemplate.postForEntity( url, request , AccessTokenResponse.class );
return response_data.getAccessToken();
}
class AccessTokenResponse{
#JsonProperty("access_token")
String accessToken;
//other props you are interested in
//+ getters/setters
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
}
}
The response:
{
"access_token": "eyJhbGciOiJIUzUxMiIsInYiOiIyLjAiLCJraWQiOiJlNDI1NDFkYi0zMTllLTRiMGYtOWIwMC04YTVlZmY4NTI2NTAifQ.eyJ2ZXIiOjcsImF1aWQiOiJjNWFjZThhNGRiNDY0NTJhM2YxNGNkZjcyZjY1MjU2NSIsImNvZGUiOiIxYldicXNVNVR3V1hDUEY5M2ZTbjdBR21xT1NKOXBUS0kiLCJpc3MiOiJ6bTpjaWQ6NjFtN2ppSXFUM2VMWDRuS0xZVUdGZyIsImdubyI6MCwidHlwZSI6MywiYXVkIjoiaHR0cHM6Ly9vYXV0aC56b29tLnVzIiwidWlkIjoianYwWWZyUDlRLWFLTlctTFVlSXRDZyIsIm5iZiI6MTY1NjMxNzM2MiwiZXhwIjoxNjU2MzIwOTYyLCJpYXQiOjE2NTYzMTczNjIsImFpZCI6IkJ4MnVOWHpHUWwtSHVDN3BITWF2NWciLCJqdGkiOiJlYTYwMDkwYS0wMWY1LTQwODctODgxMi0wNmQ2Mzk1NTI2ZGUifQ.nKiYXxCDbhQRsyR2pTu0nwegQKBHsSR9JT7CBnad5pPfBi4pVBISjGp6icRv2Nyv_L7lNzVBK8clW7Z5zM9TUg",
"token_type": "bearer",
"expires_in": 3599,
"scope": "meeting:read:admin user:master user:read:admin user:write:admin"
}
Make your life easier, not harder - use plain DTO
class AccessTokenResponse{
#JsonProperty("access_token");
String accessToken
//other props you are interested in
//+ getters/setters
}
and then
AccessTokenResponse response = restTemplate.postForObject( url, request , AccessTokenResponse.class );
response.getAccessToken(); //here you have it

Why can't I send or POST a file with RestTemplate to the server?

File fileJson = new File("answer.json");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
**body.add("answer", fileJson);**
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
String urlFinal = "url";
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.postForEntity(urlFinal, requestEntity, String.class);
System.out.println(response);
The server returns me a 400 error saying that the file was not sent in the body. I was wondering if the problem is with my code or with the server.
The file is a JSON, which must be sent in Multipart-Form-data.
I left the urlFinal string with just "url" to put as an example, but there is a valid url, as I've already done tests.
You need add filename and BAOS to MultiValueMap body, add this:
File fileJson = new File("answer.json");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("filename", fileJson.getName());
body.add("file", new ByteArrayResource(Files.readAllBytes(fileJson.toPath()));
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
String urlFinal = "url";
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.postForEntity(urlFinal, requestEntity, String.class);
System.out.println(response);
But is not the best mode, because you can change your code for use this method:
#Service
public class FileUploadService {
private RestTemplate restTemplate;
#Autowired
public FileUploadService(RestTemplateBuilder builder) {
this.restTemplate = builder.build();
}
public void postFile(String filename, byte[] someByteArray) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
// This nested HttpEntiy is important to create the correct
// Content-Disposition entry with metadata "name" and "filename"
MultiValueMap<String, String> fileMap = new LinkedMultiValueMap<>();
ContentDisposition contentDisposition = ContentDisposition
.builder("form-data")
.name("file")
.filename(filename)
.build();
fileMap.add(HttpHeaders.CONTENT_DISPOSITION, contentDisposition.toString());
HttpEntity<byte[]> fileEntity = new HttpEntity<>(someByteArray, fileMap);
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file", fileEntity);
HttpEntity<MultiValueMap<String, Object>> requestEntity =
new HttpEntity<>(body, headers);
try {
ResponseEntity<String> response = restTemplate.exchange(
"/urlToPostTo",
HttpMethod.POST,
requestEntity,
String.class);
} catch (HttpClientErrorException e) {
e.printStackTrace();
}
}
}

How do I mock RestTemplate exchange using junit 5 (Jupiter)

I tried with below code but in response body I got empty records.
Please help me on below code.
Java Code:
public Customer getCustomers(String customerId, String authorization) {
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.set("Authorization", authorization);
HttpEntity<Customer> request = new HttpEntity<>(headers);
Map<String, Object> params = new HashMap<>();
params.put("CustomerId", customerId);
String url = "https://localhost:8080/api/customer/{CustomerId}/get";
ResponseEntity<Customer> response = restTemplate.exchange(
url,
HttpMethod.GET,
request,
Customer.class,
params
);
Customer customer = null;
if (response != null && response.getBody() != null) {
customer = response.getBody();
}
return customer;
}
Test Code:
#Test
public void testGetCustomersSuccess() {
Customer customer = new Customer();
customer.setCountryCode("countryCode");
customer.setCreatedFrom("createdFrom");
customer.setCustomerlandline("224153");
customer.setCustomermobile("1522252");
customer.setEmail("email");
customer.setFirstname("firstName");
customer.setFiscalCode("fiscalCode");
customer.setFirstname("lastName");
customer.setId("5");
MultiValueMap<String, String> headers=new LinkedMultiValueMap<>();
headers.set(Authorization,"12152");
ResponseEntity<Customer> response=new ResponseEntity<Customer>(HttpStatus.OK);
when(restTemplate.exchange(Mockito.any(String.class),
Mockito.<HttpMethod> any(),
Mockito.<HttpEntity<Customer>> any(),
Mockito.<Class<Customer>> any(),
Mockito.<String, Object> anyMap()))
.thenReturn(response);
assertEquals(response.getBody(),serviceClientImpl.getCustomers("5", "12152"));
}
You need to set the value of customer in your response.
The values you are setting in customer object is not being used anywhere.
Try this:
ResponseEntity<Customer> response=new ResponseEntity<Customer>(customer,HttpStatus.OK);

How to return base64 Image from GET request through proxy?

Here is my code. It seems to alter my base64 image incorrectly.
#RequestMapping(value = "/get/**", method = RequestMethod.GET)
public String home(Locale locale, Model model, HttpServletRequest request) {
String query = request.getRequestURI().replaceAll("/OtkProxy/get/", "");
final String uri = "http://110.25.114.11/"+query;
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject(uri, String.class);
model.addAttribute("data", result);
return "home";
}
What am I doing wrong?
Managed do it that way:
#RequestMapping(value = "/getphoto/**", method = RequestMethod.GET)
public void homephoto(HttpServletResponse response, HttpServletRequest request) {
String query = request.getRequestURI().replaceAll("/OtkProxy/getphoto/", "");
//final String uri = "http://10.25.114.11/"+query;
final String uri = "http://qmatic.faceis.ru/"+query;
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_JPEG);
HttpEntity entity = new HttpEntity(headers);
String res = restTemplate.getForObject(uri, String.class, entity);
response.setContentType("image/jpeg");
try {
response.getOutputStream().print(res);
}
catch (Exception ex)
{
System.out.println("getphoto - " + ex.getMessage());
}
}

How to use Spring RestTemplate instead of Apache Httpclient?

I want to use Spring RestTemplate instead of Apache HttpClient for working with a remote API
With HttpClient
// build request JSON
JSONObject json = new JSONObject();
json.put("username", username);
json.put("serial", serial);
json.put("keyId", keyId);
json.put("otp", otp);
String json_req = json.toString();
// make HTTP request and get response
HttpPost request = new HttpPost(AuthServer);
request.setHeader("Content-Type", "application/json");
request.setEntity(new StringEntity(json_req));
response = client.execute(request);
With RestTemplate
Map<String, String> paramMap = new HashMap<String,String>();
paramMap.put("username", userName);
paramMap.put("serial", serial);
paramMap.put("keyId", keyId);
paramMap.put("otp", otp);
String mapAsJson = new ObjectMapper().writeValueAsString(paramMap);
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<String>(mapAsJson,requestHeaders);
try {
ResponseEntity<String> response = restTemplate.exchange(AuthServer, HttpMethod.POST, request, String.class);
return response.getHeaders();
} catch (HttpClientErrorException e) {
return null;
}
}
The code with HttpClient works but that with RestTemplate does not. I don't know how to use StringEntity in RestTemplate.
Spring version is 3.0.0, and JVM is 1.6.
RestTemplate is better suited to working with objects. As an example:
AuthenticationRequest.java
class AuthenticationRequest {
private String username;
private String serial;
private String key;
private String otp;
}
AuthenticationResponse.java
class AuthenticationResponse {
private boolean success;
}
AuthenticationCall.java
class AuthenticationCall {
public AuthenticationResponse execute(AuthenticationRequest payload) {
HttpEntity<AuthenticationRequest> request = new HttpEntity<AuthenticationRequest>(payload, new HttpHeaders());
return restTemplate.exchange("http://www.domain.com/api/endpoint"
, HttpMethod.POST
, request
, AuthenticationResponse.class).getBody();
}
}
These classes can be used as follows:
if(new AuthenticationCall().execute(authenticationRequest).isSuccess()) {
// Authentication succeeded.
}
else {
// Authentication failed.
}
All of this requires there to be a JSON library such as Jackson or GSON on the classpath.

Categories

Resources