RestTemplate authentication while setting userName and password - spring

I have a curl command but I want to pass this information with userName and password while calling the rest API, every thing I have tried doesn't work.
curl -u E-BOARD:HVRid992Xl740NnWOkjk -X GET --header 'Accept: application/json' 'https://XXXXXX.fr/AAAAAA/BBBBB/v1/details?abc=hsdfh&zyx=asdfsdf
My rest API looks something like this
String url = new StringBuilder(urlConfigService.getProfiles().getBaseUrl()).append(relativeUrl).toString();
**String hiddenAccess = "ASHGHGHJ:HVRid992Xl740NnWOkjk";**
// #formatter:off
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
.queryParam("refEboard", refEboard)
.queryParam("idLangue", "FR");
// #formatter:on
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
requestHeaders.add("Authorization", hiddenAccess);
HttpEntity<?> httpEntity = new HttpEntity<String>(requestHeaders);
restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
String result =
restTemplate.exchange(builder.build().toUri(), HttpMethod.GET, httpEntity, String.class).getBody();
return (T) new Gson().fromJson(result, type.getClass());

It seems to me that you are trying to send basic authentication credentials. To do this you have to encode username and password in Base64 and set request header like this:
Basic (username:password Base64 Encoded)
This is how you do it:
RestTemplate restTemplate = new RestTemplate();
HttpHeaders header = new HttpHeaders();
String auth = username + ":" + password;
byte [] authentication = auth.getBytes();
byte[] base64Authentication = Base64Utils.encode(authentication);
String baseCredential = new String(base64Authentication);
header.add(HttpHeaders.AUTHORIZATION, "Basic " + baseCredential);
header.setAccept(Collections.singletonList(MediaType.TEXT_PLAIN));
HttpEntity<String> request = new HttpEntity<String>(header);
restTemplate.exchange(builder.build().toUri(), HttpMethod.GET, request, String.class);

Related

How to add file as Form data in Http request in spring boot

I'm writing test cases to a controller in spring boot which takes MultipartFile as RequestParam. In the test case method I'm using TestRestTemplate.exchange() to send the request to the controller. I'm not sure how to make the Headers correctly so that I can send the request.
The Postman curl looks like this:
curl --location --request POST 'localhost:9091/response/upload'
--form 'file=#"/home/adityak/Downloads/ClientLog_NEW.txt"'
For file uploading to any service or endpoint
private String testExchange(File file) {
//add file
LinkedMultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
params.add("file", new FileSystemResource(file));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity =
new HttpEntity<>(params, headers);
ResponseEntity<String> responseEntity = restTemplate.exchange(
"/upload-file",
HttpMethod.POST,
requestEntity,
String.class);
HttpStatus statusCode = responseEntity.getStatusCode();
if (statusCode == HttpStatus.ACCEPTED) {
result = responseEntity.getBody();
}
return result;
}

How to set paypal get access token param of POSTMAN call in Spring Boot (Java) REST TEMPLATE call

I can get access token with POSTMAN call by passing below parameters,
POST URL : https://api.sandbox.paypal.com/v1/oauth2/token
Authorization
Type : Basic Auth
Username : MY_CLIENT_ID
Password : MY_SECRET
Headers
Content-Type : application/x-www-form-urlencoded
Body
grant_type : client_credentials
Please let me know, how can I set above details in REST TEMPLATE call in spring boot to get access token
you can refer to the following code
public void run(String... args) throws Exception {
StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
RestTemplate restTemplate = new RestTemplateBuilder()
.setConnectTimeout(Duration.ofSeconds(60))
.additionalMessageConverters(stringHttpMessageConverter)
.build();
String uri = "https://api.paypal.com/v1/oauth2/token?grant_type=client_credentials";
String username = "yourAppClientId";
String password = "yourAppPwd";
HttpHeaders basicAuth = new HttpHeaders() {{
String auth = username + ":" + password;
byte[] encodedAuth = Base64.encodeBase64(
auth.getBytes(StandardCharsets.US_ASCII));
String authHeader = "Basic " + new String(encodedAuth);
set("Authorization", authHeader);
}};
ResponseEntity<String> response = restTemplate.exchange
(uri, HttpMethod.POST, new HttpEntity<>(basicAuth), String.class);
System.out.println(response.getBody());
}

Spring RestTemplate exchange return 204 and in postman 200

I'm turning around since this morning , i've this method that return NO_CONTENT (204) in Java, but when i execute the same URL in postman i got Content (200)
String encodedCredentials = getEncodedCredentials(deviceConfigurationInstance);
RestTemplate restTemplate = getRestTemplate(url, deviceConfigurationInstance);
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + encodedCredentials);
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Accept", "*/*");
HttpEntity<String> request = new HttpEntity<String>(headers);
ResponseEntity<T> response = restTemplate.exchange(url, HttpMethod.GET, request, retType);
return response;
I've add the credential in postman also
What i've forgot in Java ?
Note : retType has Class<T> as type

org.springframework.web.client.HttpClientErrorException: 401 Unauthorized

I have web service URL:
http://myservice.local/aprovalanduser/?format=json&Name=India
When I am calling this URL using
resttemplate httpsrestTemplate.getForObject(uri, userdetails[].class)
I am getting error:
org.springframework.web.client.HttpClientErrorException: 401 Unauthorized
in the web service method:
method: "GET",
data: xmlData,
contentType: "application/xml",
dataType: "xml",
async: true,
crossDomain: false,
I am setting the header only for XML like below:
headers.setContentType(MediaType.APPLICATION_XML);
Here is the code which does basic authentication as suggested by #ekem chitsiga
String plainCreds = "username:password";
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Creds);
HttpEntity<String> request = new HttpEntity<String>(headers);
RestTemplate restTemplate = new RestTemplate();
String url = "http://myservice.local/aprovalanduser/?format=json&Name=India";
ResponseEntity<Object> response = restTemplate.exchange(url, HttpMethod.GET, request, Object.class);
response.getBody();
Http status code 401 means that you need to supply credentials to access the service. The way you present the credentials dependends on the authentication mechanism used by the service
For example if it uses Basic Authentication then you need to add a Authorization request header with Basic prefix and a base64 encoded combination of username and password separated by :
String plainCreds_usuario = Constants.CREDENCIAL_REST_API_ODATA_USUARIO;
String plainCreds_password = Constants.CREDENCIAL_REST_API_ODATA_PASSWORD;
String plainCreds = plainCreds_usuario+":"+plainCreds_password;
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Creds);
HttpEntity<String> request = new HttpEntity<String>(headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Object> response = restTemplate.exchange(Constants.getRutaApiOdataHttp() + Constants.WS_REST_API_ODATA_GET_EMPRESAS, HttpMethod.GET, request, Object.class);
response.getBody();
if(response != null && response.getBody() != null){
System.out.println("YES");
System.out.println(response.getBody().toString());
}
else
{
System.out.println("NONES");
}

HTTP POST using JSON in Spring Rest

I would like to make a simple HTTP POST using Spring RestTemplate.
the Wesb service accept JSON in parameter for example: {"name":"mame","email":"email#gmail.com"}
public static void main(String[] args) {
final String uri = "url";
RestTemplate restTemplate = new RestTemplate();
// Add the Jackson message converter
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
// create request body
String input = "{ \"name\": \"name\", \"email\": \"email#gmail.com\" }";
JsonObject request = new JsonObject();
request.addProperty("model", input);
// set headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "Basic " + "xxxxxxxxxxxx");
HttpEntity<String> entity = new HttpEntity<String>(request.toString(), headers);
// send request and parse result
ResponseEntity<String> response = restTemplate
.exchange(uri, HttpMethod.POST, entity, String.class);
System.out.println(response);
}
When I test this code I got this error:
Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 400 Bad Request
when I call webservice with Curl I have correct result:
curl -X POST -H "Authorization: Basic xxxxxxxxxx" --header "Content-Type: application/json" --header "Accept: application/json" -d "{ \"name\": \"name\", \"email\": \"email#gmail.com\" } " "url"
try to remove model from the code, as i can see in your curl request you didn't use model attribute and everything works. try this:
public static void main(String[] args) {
final String uri = "url";
RestTemplate restTemplate = new RestTemplate();
// Add the Jackson message converter
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
// create request body
String input = "{\"name\":\"name\",\"email\":\"email#gmail.com\"}";
// set headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "Basic " + "xxxxxxxxxxxx");
HttpEntity<String> entity = new HttpEntity<String>(input, headers);
// send request and parse result
ResponseEntity<String> response = restTemplate
.exchange(uri, HttpMethod.POST, entity, String.class);
System.out.println(response);
}

Resources