413 request entity too large issue in HTTP Get method call - spring-boot

Please don't mistake it as already asked question. The main difference here is, this issue is coming in Get method call. All the solutions discussed here or other places talks about either POST method or multipart form data.
Configuration I have provided is as below:
String url = env.getProperty(ApplicationConstants.PMCC_MANAGER_REGION_QUERY_URL);
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url).queryParam("inTIS_PMA_NUMBER","ALL");
URI uri = builder.build().toUri();
RestTemplate restTemplate = getRestTemplateBuilder().build();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);
private RestTemplateBuilder getRestTemplateBuilder() {
Integer connectionTimeOut = 2000;
Integer readTimeOut = 3000;
RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();
restTemplateBuilder.setConnectTimeout(connectionTimeOut);
restTemplateBuilder.setReadTimeout(readTimeOut);
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setBufferRequestBody(false);
restTemplateBuilder.requestFactory(factory);
return restTemplateBuilder;
}
This code is part of Spring Boot application and deployed in WebLogic server.

Related

Could Not call Oauth 2 from RestTemplate

I tried to call oauth 2 using Spring RestTemplate but ended up with this error 404 Not Found: [{"message":"no Route matched with those values"}]
below is my code .OauthRequest is class created by me .
String oauthurl = serverurl + GET_TOKEN;
HttpHeaders headers = buildHeader();
OauthRequest oathRequest = new OauthRequest();
oathRequest.setClient_id(clientid);
oathRequest.setClient_secret(clientsecret);
oathRequest.setAuthenticated_userid(usercode);
oathRequest.setScope(scope);
oathRequest.setGrant_type(grantTypePassword);
oathRequest.setProvision_key(key);
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Host", hostname);
headers.set("Accept-Version", "1.0");
headers.set("Content-Length", MAX_TRANSFER_SIZE);
HttpEntity<OauthRequest> requestEntity = new HttpEntity<>(oathRequest, headers);
ResponseEntity<OauthResponse> result = restTemplate.exchange(oauthurl, HttpMethod.POST, requestEntity,
OauthResponse.class);
return result.getBody();
Is there any limitation on calling from RestTemplate rather than using OAuth2RestTemplate .My understanding is it will be achievable using RestTemplate also.Must i use OAuth2RestTemplate ?Any help?
RestTemplate does not set hostname in
headers.set("Host", hostname);
Adding below it worked
System.setProperty("sun.net.http.allowRestrictedHeaders", "true");

Sample Spring RestTemplate implementation

I want to push some archived files into GITHub from my local spring application.
repos/{:user}/{:repo}/git/refs/heads/{:branchname}
{
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("XXXXXX", 8080));
requestFactory.setProxy(proxy);
RestTemplate restTemplate = new RestTemplate(requestFactory);
String url = new String("https://api.github.com/repos/XXX/MyApplication/git/refs/heads/XXX");
Map<String, String> req = new HashMap<String,String>();
req.put("sha", "9a7fd370e28ea7a4bc8242e7f234s5ed07042cb88");
String jsonObject = JSONParser.quote(payload);
HttpEntity<Object> httpEntity = new HttpEntity<>(headers1);
restTemplate.exchange(url, HttpMethod.POST,httpEntity,Object.class);
}
Error: Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 404 Not Found
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:63)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:531)
Using the below POST API, I get '404 not found error'.
Method : POST
URL : https://api.github.com/repos/{:user}/{:repo}/git/refs/heads/{:branchname}
{
"sha": "{:new-commit-sha}"
}
Can you any one provide sample Spring RestTemplate implementation for above api?
i found issue in above scenario. for this above POST client userId and password in Headers and it is wrong.
we need to provide userId and Password in BasicAutherizationInceptors class like below.
resttemplate.getInterceptors().add(new BasicAutherizationInterceptor(userId,Pwd));

spring boot application periodic post request via resttemplate in json

Below is my spring boot code snippet to post json data to server url every few min to tell that I am alive and running(which loads my json input data to db). purpose of this post request is to update the status on application monitoring tool.
What could be the right approach to implment this behaviour in my spring boot app? Is their any decorator api to do such post request to url, every few miuntes through out the application.? how can I know the time of successful post request to do next post request ? Please help me. Thanks in advance.
RestTemplate restTemplate = new RestTemplate();
String url = "endpoint url";
String requestJson = "{\"I am alive\":\"App name?\"}";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers);
String answer = restTemplate.postForObject(url, entity, String.class);
System.out.println(answer);
Why don't you use the #Scheduled annotation? This will seutes.nd your REST request every 3 minutes...
#Component
public class Heartbeater {
#Scheduled(fixedDelay = 180000)
public void heartbeat() {
// Your code is below...
RestTemplate restTemplate = new RestTemplate();
String url = "endpoint url";
String requestJson = "{\"I am alive\":\"App name?\"}";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers);
String answer = restTemplate.postForObject(url, entity, String.class);
System.out.println(answer);
}

Authentication for POST REST API with spring restTemplate

I want to use Spring RESTTemplate to post an Object to a web server and get one back.
Here the piece of code:
String authStringEncoded =
Base64.getEncoder().encodeToString
("582f3e4a9e933168ea1048e6:98c6f2736c5f02279d767ce7ddfe7e5d".getBytes("utf-8"));
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + authStringEncoded);
HttpEntity<String> request = new HttpEntity<String>(headers);
RestTemplate rt = new RestTemplate();
rt.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
rt.getMessageConverters().add(new StringHttpMessageConverter());
String uri = new String(REGISTERING_NEW_DEVICES.replace("{devicetype-id}", KIT_TYPE_ID));
TdkDevice deviceC3DF86B = new TdkDevice();
deviceC3DF86B.setId("C3DF86B");
deviceC3DF86B.setPal("44CFFFC9D5F8E8B2F36");
DeviceRegistration deviceRegistration = new DeviceRegistration();
deviceRegistration.getIds().add(deviceC3DF86B);
rt.postForObject(uri, HttpMethod.POST, request, deviceRegistration, DeviceRegistration.class);
But I got a compilation error:
The method postForObject(String, Object, Class<T>, Object...) in the type RestTemplate is not applicable for the arguments (String, HttpMethod, HttpEntity<String>, DeviceRegistration,
Class<DeviceRegistration>)
Your service call should be like following:
rt.postForObject(uri, request, DeviceRegistration.class);
According to spring RestTemplate api, postForObject method's parameters should be following:
Parameters:
url - the URL
request - the Object to be POSTed (may be null)
responseType - the type of the return value
uriVariables - the variables to expand the template
API Reference

Spring RestTemplate redirect 302

I'm trying to use spring rest template to do a post request to login in.
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
LinkedMultiValueMap<String, Object> mvm = new LinkedMultiValueMap<String, Object>();
mvm.add("LoginForm_Login", "login");
mvm.add("LoginForm_Password", "password");
ResponseEntity<String> result = restTemplate.exchange(uriDWLogin, HttpMethod.POST, requestEntity, String.class);
My ResponseEntity status is 302, i want to follow this request to get the body response , because i didn't get the body for this request.
18:59:59.170 MAIN [http-nio-8080-exec-83] DEBUG c.d.s.c.DemandwareCtlr - loginToSandbox - StatusResponse - 302
18:59:59.170 MAIN [http-nio-8080-exec-83] DEBUG c.d.s.c.DemandwareCtlr - loginToSandbox - BodyResponse -
What can I do to solve this problem ?!
The redirection is followed automatically if the request is a GET request (see this answer). To make it happen on POST requests, one option might be to use a different request factory, like HttpComponentsClientHttpRequestFactory, and set it to use an HttpClient with the required settings to follow the redirect (see LaxRedirectStrategy):
final RestTemplate restTemplate = new RestTemplate();
final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
final HttpClient httpClient = HttpClientBuilder.create()
.setRedirectStrategy(new LaxRedirectStrategy())
.build();
factory.setHttpClient(httpClient);
restTemplate.setRequestFactory(factory);
I haven't tested, but this should work.

Resources