How do I send List<T> with HTTPEntity in rest Template - resttemplate

Exception in thread "main"
org.springframework.web.client.HttpClientErrorException: 400 Bad
Request
And my code is
RestTemplate restTemplate = new RestTemplate();
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(Constants.ADD_EVENT_URL)
.queryParam("dataMap", eventsList);
String paramUrl = builder.build().encode().toString();
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<List<T>> httpEntity = new HttpEntity<List<T>>(eventsList, requestHeaders);
ResponseEntity<String> eventsAdded = restTemplate.exchange (paramUrl, HttpMethod.POST, httpEntity,String.class);

I realize this is a little old, but I presume the client is set up to receive a collection of some type?
An HTTP 400 happens from when your request is malformed, so either your entity is not correct, or you have not provided the correct path parameters, request parameters, and / or entity information.
From the URI being constructed there it looks like you are trying to pass the list as a querystring parameter and as a part of the request body, which is redundant.
Maybe try something like
UriComponentsBuilder builder = UriComponentsBuilder.fromUrlString(Constants.ADD_EVENT_URL);
...
HttpEntity<List<T>> httpEntity = new HttpEntity<List<T>>(eventsList, requestHeaders);
ResponseEntity<String> eventsAdded = restTemplate.exchange (builder.toUriString(), HttpMethod.POST, httpEntity, String.class);
OR
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(Constants.ADD_EVENT_URL)
.queryParam("dataMap", eventsList);
...
ResponseEntity<String> eventsAdded = restTemplate.exchange (builder.toUriString(), HttpMethod.POST, null, String.class);

Related

Pass FromHeader the httpClient to webapi 6.0

Below is the code, I have used to call the api. However, May I know how to pass http header
for example
Get customer has a header [FromHeader] field.
string uri = "https://localhost:7290/customers";
var response = await _httpClient.GetAsync(uri);
HttpClient GetAsync() is a shortcut for generating an instance of a HttpRequestMessage set to perform a GET for the specified URI and passing it to the SendAsync() method.
You can create your own request message instance and append additional details such as headers, then use the SendAsync() method yourself.
var request = new HttpRequestMessage(HttpMethod.Get, uri);
request.Headers.Add("header", "value");
var response = await client.SendAsync(request);
https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httprequestmessage?view=net-6.0

Resttemplate response in ????? how to resolve this

API response content-type coming as utf-16 but it should be in utf-8 format..am using spring 3.1.0 version. Am passing header and body to resttemplate. Responce comming like ???????????
Help me on this
My Code
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.set("AuthenticationToken", authenticationToken);
headers.set("ExactSubscriptionId", subscriptionId);``
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity2 = new HttpEntity<String>(lis.toString(),headers2);
ResponseEntity<String> irnResponce2 = restTemplate2.exchange(Url, HttpMethod.POST, entity2,String.class);
i have used resolve this below code
restTemplate2.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
and also tried
headers.add("Accept-Charset", "utf-8");
but in spring 3.1.0 version StringHttpMessageConverter not allowing constructor
I need to resolve in this version only plz anyone help on this
RestTemplate restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> c = restTemplate.getMessageConverters();
for(HttpMessageConverter<?> mc :c){
if (mc instanceof StringHttpMessageConverter) {
StringHttpMessageConverter mcc = (StringHttpMessageConverter) mc;
mcc.setWriteAcceptCharset(false);
}
}
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setAcceptCharset(Arrays.asList(Charset.forName("UTF-8")));
HttpEntity<String> entity = new HttpEntity<String>(jsonPayload, headers);
restTemplate.postForEntity(postResourc`enter code here`eUrl, entity, String.class);

Spring Resttemplate : how to post file and common String data at the same time

I meet a request to upload files with spring resttemplate to upload files
with http header "multipart/form-data", also some other normal parameters need to be posted. how to implements that?
you can use the following code in your application to have both multipartfile and normal request parameters at the same time.
Replace the url with your own.
replace param and value according to your normal parameters.
String url ="http://example.com";
String fileAbsPath ="absolute path of your file";
String fileName = new File(fileAbsPath).getName();
Files.readAllBytes(Paths.get(fileAbsPath));
MultiValueMap<String, Object> data = new LinkedMultiValueMap<String, Object>();
ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(Paths.get(fileAbsPath))) {
#Override
public String getFilename() {
return fileName;
}
};
data.add("file", resource);
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set("file","application/pdf");
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
.queryParam("param1", "value1")
.queryParam("param2", "value2")
HttpEntity<> entity =
new HttpEntity<> (data, requestHeaders);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> result =restTemplate.exchange(
builder.toUriString(),
HttpMethod.POST,
entity,
String.class);
System.out.println(result.getBody());
you can use this code.
HttpHeaders headers = getCASHeaders(MediaType.MULTIPART_FORM_DATA);
LinkedMultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
params.add("fileField", new FileSystemResource(""));//get file resource
params.add("stringfield", stringPayload);
HttpEntity requestEntity = new HttpEntity<>(params, headers);
ResponseEntity<CasAssetApiResponse> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
This will send post call with two param, you can add more according to your wish.
Please have a look at this stackoverflow answer as well
I got the error "cannot be cast to java.lang.String" although my code does not have any casting.

RestTemplate request with braces ("{", "}")

I want to send request through RestTemplate. But my url has braces ('{', '}'), and therefore I have exception: "Not enough variable values available to expand ...".
I try do it through uri
UriComponentsBuilder builder = UriComponentsBuilder.fromPath(url);
UriComponents uriComponents = builder.build();
URI uri = uriComponents.toUri();
But I got new exception:"protocol = https host = null".
How I can send request with my URL? In URL must be braces.
My code:
String url = "https://api.vk.com/method/execute?code=return[API.users.search({"count":1})];&access_token...
String result = restTemplate.getForObject(url, String.class);
Below code encrypts the uri using UriComponentsBuilder, adds query params using RestTemplate and also sets HttpHeaders if any.
public HttpEntity<String> getEntityByUri() {
String req = "https://api.vk.com/method/execute";
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(req)
.queryParam("code",
"return[API.users.search({"count":1})]");
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.ALL));
HttpEntity<String> httpEntity = new HttpEntity<String>(headers);
return new RestTemplate().exchange(builder.build().encode().toUri(), HttpMethod.GET, httpEntity, String.class);
}
Hope this helps and good luck!

spring mvc http proxy

I would like to write a spring MVC Controller class that just take any http request in input, add basic authentication headers to it and forward this request to another server.
I try something like this without success.
#Controller
#RequestMapping("/proxyws")
public class ProxyController {
#RequestMapping("/**")
#ResponseBody
public String mirrorRest( #RequestBody String body, HttpMethod method, HttpServletRequest request, HttpServletResponse response) throws URISyntaxException
{
String server = "localhost";
int port = 8080;
URI uri = new URI("http", null, server, port, request.getRequestURI(), request.getQueryString(), null);
RestTemplate restTemplate=new RestTemplate();
HttpEntity entity = new HttpEntity<String>(body);
String plainCreds = "APP_CLIENT:APP_PASSWORD";
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);
entity.getHeaders().add("Authorization", "Basic " + base64Creds);
ResponseEntity<String> responseEntity = restTemplate.exchange(uri, method, entity, String.class);
return responseEntity.getBody();
}
For a GET method in input, I get the following exception :
org.springframework.http.converter.HttpMessageNotReadableException: Required request body content is missing:
org.springframework.web.method.HandlerMethod$HandlerMethodParameter#8051792a
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleEmptyBody(RequestResponseBodyMethodProcessor.java:189)
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:170)
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:105)
For a POST request, I get other trouble with le basic auth headers:
java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableMap.put(Collections.java:1342)
at org.springframework.http.HttpHeaders.add(HttpHeaders.java:831)
Thanx for your help!
You cannot modify the headers of the HttpEntity object once it's instantiated. You need to pass your headers in through a different HttpEntity constructor, e.g.
public HttpEntity(T body, MultiValueMap<String, String> headers) {
this.body = body;
HttpHeaders tempHeaders = new HttpHeaders();
if (headers != null) {
tempHeaders.putAll(headers);
}
this.headers = HttpHeaders.readOnlyHttpHeaders(tempHeaders);
}
Note the initialization of this.headers: that's where the read-only copy is created.

Resources