response from post request is empty - spring-boot

I have the following WS i request from post man with the following parameters:
and i have the following from the postman console
I am trying to request the WS with the following piece of code :
logger.info("generating new token from "+URL);
expritation = new Date();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
map.add("userUid", userUid);
map.add("appUid", appUid);
map.add("ttl", ttl);
restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor(WsLogin, WsPassword));
ResponseEntity<String> response = restTemplate.postForEntity(URL, map , String.class);
return response.getBody();
I am able to see the response body in postman but the response.getBody() is emty in the java code.
Can someone explain to me why it is the case.

You mean you are seeing the response body in the Postman but not in your prog? Did you try to debug of print the response value before returning from the method?

Related

How to read response with Content-Type text/plain;charset=UTF-8 using RestTemplate

I have an API (/get-sas-token) that is returning a response with Content-Type=text/plain;charset=UTF-8.
In Postman when I hit this API it returns as sig=PAd%2By7yzue0G%2FVeMKbwvR%2F%2B5a3X8CUTablCIhS3uCuk%3D&s
The code for this API is
#GetMapping("/get-sas-token/{containerName}")
public String getSASToken(#PathVariable("containerName") String containerName)
throws InvalidKeyException, URISyntaxException, StorageException {
CloudBlobContainer appcontainer = config.blobClient().getContainerReference(containerName);
return appConfiguration.generateSASToken(appcontainer);
}
My other microservice is trying to call this RestAPI using RestTemplate via a get request. The response I'm getting in Postman has instead of special characters like �������{J�J��t�\b�`$ؐ#������iG# some weird stuff. So I guess somethings wrong with the character encoding.
P.S : If I remove the Accept-Encoding(gzip, deflate, br) header from Postman it works.How can i get it working in my code
ResponseEntity<String> imageUrl = restTemplate.exchange(
fileServiceUrl + "/get-sas-token/" + containerReference, HttpMethod.GET, request, String.class);
logger.info("imageUrl body-------->>" + imageUrl.getBody());
It prints
imageUrl body-------->>?`I?%&/m?{J..................
I have tried all the possible soultions but nothing works for me
tried this::
template.getMessageConverters()
.add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
ResponseEntity<Object> response = template.exchange(endpoint, method, entity,
Object.class);
Also this::
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.set("Accept", "application/json");

Unauthorized 401 error for GET call on stockitem

I am accessing Acumatica API using Java Spring Resttemplate. The POST call to the Login endpoint works fine. But the next call to get StockItems gets a 401 Unauthorized error.
org.springframework.web.client.HttpClientErrorException: 401 Unauthorized at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91) at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:615) at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:573) at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:544) at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:465) at
Now this works fine when I use Postman and the Chrome Restlet client. I noticed that in Restlet client the GET call to the API passes a session cookie that was set by the API in the login call. I tried passing the response headers from the login call in the GET request. But I still get a 401. I am using the standard resttemplate configuration.
HttpEntity<Credentials> entity = new HttpEntity<Credentials>(credentials, headers);
ResponseEntity<String> response = restTemplate.exchange("https://xxxx.acumatica.com/entity/auth/login",
HttpMethod.POST, entity, String.class);
HttpHeaders rHeaders = response.getHeaders();
String set_cookie = rHeaders.getFirst(rHeaders.SET_COOKIE);
if (LOG.isInfoEnabled()) { LOG.info("Response: " + response.toString()); }
if (LOG.isInfoEnabled()) { LOG.info("Set-Cookie: " + set_cookie); }
HttpEntity<String> entity2 = new HttpEntity<String>(response.getHeaders());
ResponseEntity<String> response2 = restTemplate.exchange("https://usell.acumatica.com/entity/Default/6.00.001/StockItem?$expand=Attributes,WarehouseDetails", HttpMethod.GET, entity2, String.class);
How did Acumatica API client using Java get around this problem?
I was not setting all the cookies.. this is all I had to do
List<String> cookies = response.getHeaders().get(HttpHeaders.SET_COOKIE);
HttpHeaders requestHeaders = new HttpHeaders();
for (String cookie : cookies) {
requestHeaders.add("Cookie", cookie);
}

Null response entity with 307 status code in Rest Template

I am trying to use Spring RestTemplateBuilder to call a REST web service and POST data. Here is the sample of my code.
public HttpHeaders getHttpHeaders() {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.add("Authorization", "Basic " + authToken);
requestHeaders.add("Content-Type", "application/json");
return requestHeaders;
}
public ResponseJson getData(RequestJson requestJson) {
HttpEntity<RequestJson> entity = new HttpEntity<>(requestJson, getHttpHeaders());
ResponseEntity<ResponseJson> result = restTemplateBuilder.build().postForEntity(PostUrl, entity, ResponseJson.class);
}
When I debug this, it gives status=307 and body=null for ResponseEntity. But when I call the PostUrl directly with a request body, it creates data with 201 status code.
May I know how, to figure out this 307 status and why I am getting null response ?
This works for me, using HttpComponentsClientHttpRequestFactory https://lateralcoding.blogspot.com/2018/03/Spring-RestTemplate-AutoRedirect.html

How to not escape form body characters in Spring RestTemplate when making a POST request?

I have following code where I am making a POST form request. The request body contains username and password. Password contains # characters, which is replaced by RestTemplate with %40 and I am getting "unauthorized" error as the password is wrong now.
Following is the debug info from bufferOutput(request body)
merchant_id=firstname+de-lastname%40gmail.com&password=%40Password
Here is the code snippet that is making the call.
MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
String url = "SOME_URL";
formData.add("username", "xay#gmail.com");
formData.add("password", "#name321");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String,String>> requestEntity = new HttpEntity<MultiValueMap<String,String>>(formData,headers);
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters()
.add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
restTemplate.exchange(url, HttpMethod.POST, requestEntity, Authentication.class,"321");
The question is how to tell restTemplate not to escape body data ?
Note that the request has to be a post form request and I can not use UriComponentsBuilder to fix the problem.
I think you need to add a FormHttpMessageConverter to your RestTemplate rather than a StringHttpMessageConverter.

RestTemplate POST request urlformencoded gives 400 (Bad Request)

I have the following request :
String url = "url to oauth_token";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
RestTemplate restTemplate = new RestTemplate();
String body = "grant_type=authorization_code&client_id=123&client_secret=123&"
+ "redirect_uri=https://axyz.com&code=123";
HttpEntity<Object> entity = new HttpEntity<>(body, headers);
Object token = restTemplate.exchange(url, HttpMethod.POST, entity, Object.class);
This seems to return 400 (Bad Request). I have also tried its alternatives where body is a MultiValueMap but this is what makes the most sense to me. Is there something wrong with the way I am trying the request?
The values of the POST fields should be URL encoded (you can use URLEncoder.encode(value, "UTF-8") for each value while concatenating the body string). That's why you get 400 error.
You'd better use a more convenient way to create a POST form entity with keys and values, which will URL encode your values automatically:
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("param1", "value1"));
formparams.add(new BasicNameValuePair("redirect_uri", "https://axyz.com"));
...
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);

Resources