How to get multiple set-cookie from response - resttemplate

I have a web service call that returns two Set-Cookies. From the response, I am only able to see/get one (the first one, weird. Shouldn't it be the last one?)
Using CURL
< Set-Cookie: lat=MTQ5MTMyOTE5MzYyNQ==;domain=my.company.com;path=/
< Set-Cookie: vid=some_random_text;domain=my.company.com;path=/;HttpOnly
My code:
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("Content-Type", "application/x-www-form-urlencoded");
...
MultiValueMap<String, String> payload = new LinkedMultiValueMap<String, String>();
payload.add("_charset_", "UTF-8");
...
HttpEntity<?> request = new HttpEntity<MultiValueMap<String, String>>(payload, headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
List<String> cookies = response.getHeaders().get("Set-Cookie");
Cookies only have the first cookie and length of one. I am trying to retrieve the second Set-Cookie value.

Related

How to add "application/x-www-form-urlencoded" as Content-type in .Net httpClient

I cannot add Content-type as "application/x-www-form-urlencoded". There is throwing an error. Only for the this content-type. Thank You for the attention.
using (var httpClient = new HttpClient())
{
var request = new HttpRequestMessage
{
Method = new HttpMethod("POST"),
RequestUri = new Uri(path),
};
request.Headers.Add("Accept", "application/json");
request.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
HttpResponseMessage response1 = await httpClient.SendAsync(request);
var token = await response1.Content.ReadAsStringAsync();
}
It's throwing error like that
"Misused header name, 'Content-Type'. Make sure request headers are
used with HttpRequestMessage, response headers with
HttpResponseMessage, and content headers with HttpContent objects."
The content type is a header of the content, not of the request, which is why this is failing.
One way is that you can call TryAddWithoutValidation instead of add like below:
request.Headers.TryAddWithoutValidation("Accept", "application/json");
request.Headers.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");
The other way is that you can set the Content-Type when creating the request content itself, refer to this answer.
I'v used something more complicated but it works.
var client = new HttpClient();
//headers dictionary
var dict = new Dictionary<string, string>();
dict.Add("Content-Type", "application/x-www-form-urlencoded");
//request
var req = new HttpRequestMessage(HttpMethod.Post, new Uri(url)) { Content = new FormUrlEncodedContent(dict) };
req.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencode"));
var response = await client.SendAsync(req);

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!

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

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);

Resources