How To send a Post request with RequetTemplate in Spring - java

I'm trying to send a post request with spring RequestTemplate but I always get 401 error;
using curl
C:\Users\Latitude E 5410>curl -X POST http://localhost:8080/demo.rest.springsecu
rity.oauth2.0.authentication/oauth/token -H "Accept: application/json" -d "usern
ame=user1&password=user1&client_id=client1&client_secret=client1&grant_type=pass
word&scope=read,write"
{"access_token":"abe9d772-cb29-4bd7-b41a-437e50c10652","token_type":"bearer","re
fresh_token":"bc24f370-fcd8-4ae0-b724-a4241c746b29","expires_in":299844,"scope":
"read,write"}curl: (6) Could not resolve host: application
java code used:
HttpEntity<String> request = new HttpEntity<String>(getHeadersWithClientCredentials());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON); //restTemplate.postForObject
//restTemplate.
MultiValueMap<String, String> mvm = new LinkedMultiValueMap<String, String>();
mvm.add("client_id", "client1");
mvm.add("client_secret", "client1");
mvm.add("grant_type", "password");
mvm.add("scope", "read,write,trust");
mvm.add("username", "user1");
mvm.add("password", "user1");
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(mvm, requestHeaders);
ResponseEntity<Object> response = restTemplate.exchange("http://localhost:8080/demo.rest.springsecurity.oauth2.0.authentication/oauth/token?", HttpMethod.POST, requestEntity, Object.class);
error I get
Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 401 Non-Autorisé
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:641)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:597)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:557)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:475)
at com.geofleet.calculation.TestClient.main(TestClient.java:44)

I found another solution by sending just a post request directly w, I still feel it's a bad practice to do it (passing the parameters in the url), but hey it works,
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<String> s = restTemplate.exchange("http://localhost:8080/demo.rest.springsecurity.oauth2.0.authentication/oauth/token?username=user1&password=user1&client_id=client1&client_secret=client1&grant_type=password&scope=read", HttpMethod.POST, entity, String.class);
System.out.println(s.getBody().toString());

Related

RestTemplate how remove utf8 from request?

hello i' ve the code from request a sistem but RestTemplate add always utf8 in header
example
POST /v1/documents/validation HTTP/1.1
Accept: application/json
Content-Type: multipart/form-data;charset=UTF8;boundary=gs7Tmph96b0PDkFCrOo9Y7EhtqqV3ok2agluTF
how remove charset=UTF8 ?
this is my code
RestTemplate restTemplate = getRestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.add("Content-Type", "multipart/form-data");
headers.add("FSE-JWT-Signature", getHashSignature());
headers.add("Authorization", "Bearer " + getBearerToken());
LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
FileSystemResource value = new FileSystemResource(new File(fileName));
map.add("file", value);
map.add("requestBody", requestBody.toString());
HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(map, headers);
error
"title":"InvalidRequestContent","status":400,"detail":"Request content not conform to API specification: UTF-8;boundary=Kpj8KEbP1NBn3tLmsWgbj8O6LlcGNzyp60ejoi4A"
By default RestTemplate adds the utf-8 if you use exchange(). I don't know why.
Use postForObject, ie something like this:
String serverEndPoint = "https://httpbin.org/post";
HttpHeaders headers = new HttpHeaders();
headers.setContentType("multipart/form-data");
HttpEntity<Whatever> entity = new HttpEntity<>(whateverObject, headers);
String result = restTemplate.postForObject(serverEndPoint, entity, String.class);

Getting 400 Bad Request for Rest Template Spring Boot

I have a rest Controller where i am trying to get the Token from a service using the RestTemplate in Spring Boot. The application works fine when i use Postman but from Java Application i get 400 Bad Request.
My Java Sample :
#PostMapping("/service")
private String generateAuthenticationToken() {
HttpHeaders authenticationTokenHeaders = new HttpHeaders();
authenticationTokenHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
JSONObject sfmcBUCredential = new JSONObject();
JSONObject sfmcTokenResponseObject;
sfmcBUCredential.put("grant_type", sfmcConfig.getGrant_type());
sfmcBUCredential.put("client_id", sfmcConfig.getClient_id());
sfmcBUCredential.put("client_secret", sfmcConfig.getClient_secret());
String sfmcBUCredentialString = sfmcBUCredential.toString();
System.out.println("Values before sending to POST Request are :::" + sfmcBUCredentialString);
HttpEntity<String> getTokenEntity = new HttpEntity<>(sfmcBUCredentialString, authenticationTokenHeaders);
System.out.println("Values after sending to POST Request are :::" + getTokenEntity.toString());
System.out.println("URL is :::" + GET_SFMC_ENDPOINT_URL);
//String tokenResponse = restTemplate.postForObject(GET_SFMC_ENDPOINT_URL, getTokenEntity, String.class);
ResponseEntity<String> tokenResponse = restTemplate.exchange(GET_SFMC_ENDPOINT_URL, HttpMethod.POST, getTokenEntity, String.class);
sfmcTokenResponseObject = new JSONObject(tokenResponse.getBody());
System.out.println("tokenResponse::::::::" + sfmcTokenResponseObject.getString("access_token").toString());
return sfmcTokenResponseObject.getString("access_token");
}
Logs :
Values before sending to POST Request are :::{"grant_type":"client_credentials","client_secret":"c1ae4b4a-498e-46a0-a02e-cd2378cb8db6","client_id":"Y43iLAhr4e0SoJ9KkV4vLKnGhNmS1Y3c"}
Values after sending to POST Request are :::<{"grant_type":"client_credentials","client_secret":"c1ae4b4a-498e-46a0-a02e-cd2378cb8db6","client_id":"Y43iLAhr4e0SoJ9KkV4vLKnGhNmS1Y3c"},[Content-Type:"application/x-www-form-urlencoded"]>
URL is :::https://keycloak.lab.hci.aetna.com/auth/realms/master/protocol/openid-connect/token
Try something like this:
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("grant_type", sfmcConfig.getGrant_type());
map.add("client_id", sfmcConfig.getClient_id());
map.add("client_secret", sfmcConfig.getClient_secret());
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(map, headers);
ResponseEntity<LabelCreationResponse> response =
restTemplate.exchange("url",
HttpMethod.POST,
entity,
String.class);

RestTemplateBuilder: problem sending audio to telegram api

I use RestTemaplteBuilder for send POST request to Telegram Bot API.
There was a problem creating the request to upload the audio file.
According to the documentation - https://core.telegram.org/bots/api#sending-files you need to send a request of type multipart/form-data.
Error: 413 Request Entity Too Large
MultiValueMap<String, Object> request= new LinkedMultiValueMap<String, Object>();
try {
parts.set("chat_id", "id");
parts.set("audio", (Files.readAllBytes(Paths.get(ClassLoader.getSystemResource("name.mp3").toURI()))));
} catch (Exception e) {
e.printStackTrace();
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(request, headers);
ResponseEntity<String> responseEntity = restTemplateBuilder.build().postForEntity(requestFormatter(URL_BOT_PREFIX, method), requestEntity, String.class);

Illegal character(s) in message header field: Content-Type:

Following an API where it says that i need to send this POST request :
POST https://api.vasttrafik.se/token HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Authorization: Basic UmJseEkyeTFsWVNFTTZ0Z2J6anBTa2E0R1o6Wk1nSkR0Y0pddaRGV4OTJldUxpQUdYOFExUnU=
grant_type=client_credentials&scope=<device_id>
I am trying to build the corresponding POST-req in spring boot and this is what i come up with. However i end up with the error described in the title.. any ideas?
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type:", "application/x-www-form-urlencoded");
headers.set("Authorization", "Basic UmJseEkyeTFsWVNFTTZ0Z2J6anBTa2E0R1o6Wk1nSkR0Y0paRGV4OTJldUxpQUdYOFExUnU=");
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<String> respEntity = restTemplate.exchange("https://api.vasttrafik.se/token", HttpMethod.POST, entity, String.class);
System.out.println(respEntity);

Spring RestTemplate POST Request with URL encoded data

I'm new to Spring and trying to do a rest request with RestTemplate. The Java code should do the same as below curl command:
curl --data "name=feature&color=#5843AD" --header "PRIVATE-TOKEN: xyz" "https://someserver.com/api/v3/projects/1/labels"
But the server rejects the RestTemplate with a 400 Bad Request
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("PRIVATE-TOKEN", "xyz");
HttpEntity<String> entity = new HttpEntity<String>("name=feature&color=#5843AD", headers);
ResponseEntity<LabelCreationResponse> response = restTemplate.exchange("https://someserver.com/api/v3/projects/1/labels", HttpMethod.POST, entity, LabelCreationResponse.class);
Can somebody tell me what I'm doing wrong?
I think the problem is that when you try to send data to server didn't set the content type header which should be one of the two: "application/json" or "application/x-www-form-urlencoded" . In your case is: "application/x-www-form-urlencoded" based on your sample params (name and color). This header means "what type of data my client sends to server".
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.add("PRIVATE-TOKEN", "xyz");
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("name","feature");
map.add("color","#5843AD");
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(map, headers);
ResponseEntity<LabelCreationResponse> response =
restTemplate.exchange("https://foo/api/v3/projects/1/labels",
HttpMethod.POST,
entity,
LabelCreationResponse.class);
You need to set the Content-Type to application/json. Content-Type has to be set in the request. Below is the modified code to set the Content-Type
final String uri = "https://someserver.com/api/v3/projects/1/labels";
String input = "US";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.add("PRIVATE-TOKEN", "xyz");
HttpEntity<String> request = new HttpEntity<String>(input, headers);
ResponseEntity<LabelCreationResponse> response = restTemplate.postForObject(uri, request, LabelCreationResponse.class);
Here, HttpEntity is constructed with your input i.e "US" and with headers.
Let me know if this works, if not then please share the exception.
Cheers!
It may be a Header issue check if the header is a Valid header, are u referring to "BasicAuth" header?
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED.toString());
headers.add("Accept", MediaType.APPLICATION_JSON.toString()); //Optional in case server sends back JSON data
MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<String, String>();
requestBody.add("name", "feature");
requestBody.add("color", "#5843AD");
HttpEntity formEntity = new HttpEntity<MultiValueMap<String, String>>(requestBody, headers);
ResponseEntity<LabelCreationResponse> response =
restTemplate.exchange("https://example.com/api/request", HttpMethod.POST, formEntity, LabelCreationResponse.class);
my issue, the MessageConverters contains other converters may converts then entity to json (like FastJsonHttpMessageConverter). So i added the FormHttpMessageConverter to ahead and it works well.
<T> JuheResult<T> postForm(final String url, final MultiValueMap<String, Object> body) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
return exchange(url, HttpMethod.POST, requestEntity);
}
<T> JuheResult<T> exchange(final String url, final HttpMethod method, final HttpEntity<?> requestEntity) {
ResponseEntity<JuheResult<T>> response = restTemplate.exchange(url, method, requestEntity,
new JuheResultTypeReference<>());
logger.debug("调用结果 {}", response.getBody());
return response.getBody();
}
public JuheSupplierServiceImpl(RestTemplateBuilder restTemplateBuilder) {
Duration connectTimeout = Duration.ofSeconds(5);
Duration readTimeout = Duration.ofSeconds(5);
restTemplate = restTemplateBuilder.setConnectTimeout(connectTimeout).setReadTimeout(readTimeout)
.additionalInterceptors(interceptor()).build();
restTemplate.getMessageConverters().add(0, new FormHttpMessageConverter());
}
fastjson prevent resttemplate converting other mediaTypes other than json

Categories

Resources