How to make rest client call over https? - java

How to do the resttemplate configuration to make call over https and the response will be a 302 redirect.
Trying to make rest tamplate call to a server over https with a Bearer token after authentication of the token the server do a 302 redirect.
String redirectUrl="https://example.com/redirect";
String authHeader="Bearer eyJhbGciO";
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
requestHeaders.set("Authorization", authHeader);
Map<String, Object> uriVariables = new HashMap<>();
HttpEntity<String> requestEntity = new HttpEntity<>(null, requestHeaders);
ResponseEntity<ModelAndView> modelres = restTemplate.exchange(redirectUrl,HttpMethod.GET,requestEntity, ModelAndView.class,uriVariables);
How to make rest client call over https?

You need to configure the SSL certificate to make an https call.
Get the certificate and configure.
This post may help you

Related

What is the difference between UniRest and Spring RestTemplate giving an http 400 Bad Request?

What is the difference with UniRest and Spring RestTemplate which is giving back a 400 Bad Request with apparently the same header and body sent ?
I try to reach the HubSpot API to create a BlogPost, but using RestTemplate I have a 400 Bad Request error, and using UniRest works alright (returns an OK response). However, I do not want to include a library just to make one REST call: I'd rather stick to RestTemplate.
The request data I need to send
HttpMethod: POST
URL: https://api.hubapi.com/content/api/v2/blog-posts?hapikey=*****************
Header: Content-Type: application/json
Body: (represented by a class instance as blogpostSendPost further down)
{
"name": "My first API blog post!",
"content_group_id": 351076997
}
Using RestTemplate
Setting up the request:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<BlogpostSendPost> request = new HttpEntity<>(blogpostSendPost, headers);
log(request.toString());
//LOG PRINT: <BlogpostSendPost(name=My first API blog post!, content_group_id=351076997),[Content-Type:"application/json"]>
OR in JSON
The .json() method converts my object in Json like you can see in the logs
HttpEntity<String> request = new HttpEntity<>(blogpostSendPost.toJson(), headers);
log(request.toString());
//LOG PRINT: <{"name":"My first API blog post!","content_group_id":"351076997"},[Content-Type:"application/json"]>
With .postForObject(): 400 Bad Request
BlogpostResponsePost answer = restTemplate.postForObject(
"https://api.hubapi.com/content/api/v2/blog-posts?hapikey=***********",
request,
BlogpostResponsePost.class);
With .exchange(): 400 Bad Request
BlogpostResponsePost answer = restTemplate.exchange(
"https://api.hubapi.com/content/api/v2/blog-posts?hapikey=**********",
HttpMethod.POST,
request,
BlogpostResponsePost.class);
Using UniRest: OK
HttpResponse<JsonNode> resp = Unirest
.post("https://api.hubapi.com/content/api/v2/blog-posts?hapikey=**********")
.header("Content-Type", "application/json")
.body(blogpostSendPost)
.asJson();
I am using PostMan to call my REST SpringBoot Application which is using theses Services : when I am calling the HubSpot API directly from PostMan it works fine, just like with UniRest lib.
Thanks for your help guys !!
Please refer https://community.hubspot.com/t5/APIs-Integrations/Getting-400-Bad-Request-when-trying-to-add-a-Blog-Post/td-p/306532
Instead of converting request object to json, pass request object directly. It worked for me.
// TRY 1: CONTACTS - RestTemplate - OK - contact is created (API V1)
HttpEntity request1 = new HttpEntity<>(contactSendList, headers);
ContactResponseInformations answer1 = restTemplate
.postForObject(
HubSpotConfiguration.URL_CREATE_CONTACT,
request1,
ContactResponseInformations.class);
log.info(answer1.toString()); // OK

HttpClientErrorException: 401 Unauthorized Exception in Tomcat

We are trying to access the Lithium Rest Api using HTTPS through Spring Rest Template as below
String plainCreds = lswUserName + ":" + lswPassword;
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);
ResponseEntity<String> sRawResp = restTemplate.exchange(completeURL.toString(), HttpMethod.GET, request, String.class);
Above code always gives
org.springframework.web.client.HttpClientErrorException: 401 Unauthorized Exception
There were no issues when invoking the same web service through postman, however when ever accessed through java code, getting the above 401 unauthorized exception
Previously I faced this issue with Windows OS, and I added below entry related to proxy in to catalina.bat:
JAVA_OPTS=%JAVA_OPTS% -Dhttp.proxyHost=hy**1.*****.co.in -Dhttp.proxyPort=8080`
Now we moved the entire setup to Linux OS and I get the same error. In Linux I don't have any proxy set. I checked through wget http://www.google.com and no proxy details are displayed.
How do I resolve this issue in Linux when no proxy is set?
Please Help.

no csrf token was found.issue with my rest api while sending csrf token and cookie in header

Background
I have to send some info like cookie and csrf-token(fetched from web application) as header to third party rest client using resttemplate.The way I am sending is as below:
I have set them in my yml file.
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("csrf_token", csrf_token);
headers.add("Cookie", cookie);
Snap of my postman req/res
csrf issue postman
I am stuck here because with same token i am able to hit the rest client directly with postman but i am facing above issue with my own API which isinternally calling client using resttemplate.
what is the way to send the csrf token if my approach is wrong.

How to do OAuth 2 API call and get the response

I want to create a Spring boot application, that will call an API through OAuth2 process.
I've already checked this but can some explain it to me in a simple way.
All I have is the URL (that gets the Bearer token), Client ID and Client Secret.
Once the bearer token is retrieved I want to get the call the actual API with the retrieved bearer token put in the header, So I get the response.
In Spring,
you can use the RestTemplate.exchange method to make API calls.
Since the API is secured using an OAuth2.0 - Access token (bearer token),
the token must be passed in the "Authorization" header.
Try the code shown below to make an API call with header request:
String url = "https://you-api-url";
RestTemplate restTemplate = new RestTemplate();
// set the headers
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Bearer " + token_value);
HttpEntity entity = new HttpEntity(headers);
// send the GET request
HttpEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
// display the response
System.out.println("Response" + response.getBody());
Hope it helps!

How to set the default header for all requests in apache http client?

For example the default user agent could be set like:
client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, someName);
But how to set the "Accept" header?
HttpClient 4.3 now allows configuring a collection of default headers on the client itself:
Header header = new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json");
List<Header> headers = Lists.newArrayList(header);
HttpClient client = HttpClients.custom().setDefaultHeaders(headers).build();
HttpUriRequest request = RequestBuilder.get().setUri(SAMPLE_URL).build();
client.execute(request);
Now, all requests executed by that client will be send with the default headers.
Hope that helps.

Categories

Resources