Get Cookie By name after a restTemplate call - java

I'm sending a request ro a service that set a cookie in the response :
HttpEntity<String> response = restTemplate.exchange
(myUrl,
HttpMethod.GET,
new HttpEntity<>(headers),
String.class);
I found that I can extract the cookie using this line of code :
String set_cookie = response.getHeaders().getFirst(HttpHeaders.SET_COOKIE);
However this returns: name_of_cookie=value_of_cookie
I know that I can make a String processing to extract the value of the cookie by name, but I want to find a better solution in the manner of :
response.getHeaders().getCookieValueByName(cookie_name)
The getCookieValueByName function do not exsist. Is there a function that does what I want to do ?

Related

How to call GET api with query params having special chars{&,(,),'} using spring rest template

Below was the code used to encode uri having query params using UriComponentsBuilder
String uri = "http://hostname/api/items"
// api expected with params --> http://hostname/api/items?filter=IN('123') and id eq '123_&123'
restTemplate.exchange(UriComponentsBuilder.fromUriString(uri).queryParam("filter","IN('123') and id eq '123_&123'").encode().toUriString(), HttpMethod.GET, request, Response_Entity.class)
When above code is called, somehow at api side, i was getting 2 query params with keys -->filter & 123
How to handle it correctly using ?
try encoding query param by using URLEncoder.
String param = "IN('123') and id eq '123_&123'";
String encodedParam = URLEncoder.encode(param, Charset.defaultCharset()));
restTemplate.exchange(UriComponentsBuilder.fromUriString(uri).queryParam("filter",encodedParam).toUriString(), httpMethod, httpEntity, Some_Entity.class)
https://www.baeldung.com/java-url-encoding-decoding
Somehow query params are encoded and at api side, by default these are retrieved correctly after decoding, if i use toURI() of UriComponentsBuilder
Same was not working if i convert it to string using toUriString
Below is the code which worked for me.
URI uri = UriComponentsBuilder.fromUriString(uri)
.queryParam("filter",encodedParam)
.encode()
.build()
.toUri();
restTemplate.exchange(uri, HttpMethod.GET, request, Response_Entity.class)

JAVA API , JERSEY / POST not working

So I have in my code POST method :
#POST
#Path("/send/{userPost}")
#Consumes(MediaType.APPLICATION_JSON)
#Produces("application/json")
public Response sendUser(#PathParam("userPost") String userPost ) {
List<Post>userPosts = new ArrayList();
Post post = new Post(99,userPost,"Bartek Szlapa");
userPosts.add(post);
User user = new User(99,"Bartek","Szlapa",userPosts);
String output = user.toString();
return Response.status(200).entity(output).build();
}
unfortunately its not working. I'm getting 404 error. Server is configured correctly because other methods work perfectly. Funny thing is that when I remove {userPost} , parameter : #PathParam("userPost") String userPost and send empty request : http://localhost:8080/JavaAPI/rest/api/send it works - I'm getting new User object with null at some fields. Do you know why I cannot send parameter ? Thanks in advance for help! :)
What you are sending is not a path parameter to send your value as a path parameter based on your api , let us say you are trying to send "test"
http://localhost:8080/JavaAPI/rest/api/send/test
if you want to use query params
#POST
#Path("/send")
#Consumes(MediaType.APPLICATION_JSON)
#Produces("application/json")
public Response sendUser(#QueryParam("userPost") String userPost ) {
and your request should be
http://localhost:8080/JavaAPI/rest/api/send?userPost=test
Your "userPost" parameter is not in the Path : localhost:8080/JavaAPI/rest/api/send?=test
You defined this path :
#Path("/send/{userPost}")
So, your URI should be :
localhost:8080/JavaAPI/rest/api/send/test

How to extract parameters from an object to show in parameters in documentation

I have the following API endpoint:
#ApiResponses(
value = {
#ApiResponse(code = 200, message = "OK",
responseHeaders = {
#ResponseHeader(name = "X-RateLimit-Limit", description = "The defined maximum number of requests available to the consumer for this API.", response = Integer.class),
#ResponseHeader(name = "X-RateLimit-Remaining", description = "The number of calls remaining before the limit is enforced and requests are bounced.", response = Integer.class),
#ResponseHeader(name = "X-RateLimit-Reset", description = "The time, in seconds, until the limit expires and another request will be allowed in. This header will only be present if the limit is being enforced.", response = Integer.class)
}
)
}
)
#ApiOperation(httpMethod = "GET", hidden = false, nickname = "Get Network Availability in JSON", value = "Get network availability for a product", response = AvailableToPromise.class, position = 1)
#RequestMapping(value = "/{product_id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> networkAvailabilityJsonResponse(
#RequestHeader HttpHeaders headers,
#PathVariable("product_id") String productId,
#Valid NetworkAvailabilityCmd cmd, //query params
BindingResult result)
throws Exception {}
}
Certain parameters, such as key are taken from the query and mapped into this object through Spring MVC.
However, in the parameters section of my endpoint in the swagger-ui, it's showing me a few odd things:
None of the variables that are in NetworkAvailabilityCmd show in this parameters list, and cmd itself shows as being located in the request body (it's actually located in the query). Is there a way to hide cmd and extract the params inside this object to show on the params list? I'd like the params list to look like this (with more params):
I'm able to do this if I use #ApiImplicitParams on the method endpoint, and write out each of the params. However, this NetworkAvailabilityCmd is used for many endpoints, and having the list of params on each endpoint is very messy. Being able to extract the variables from in the object would be far cleaner, and would prevent people from forgetting to add the entire list to new endpoints.
I imagine that it requires an annotation on NetworkAvailabilityCmd cmd, and potentially something on the variables in that class, but I can't seem to find what I'm looking for in the docs.
Thanks!
I found out that adding #ModelAttribute worked magically. This annotation is from Spring.

java rest client for mixed parameter forms

I have a rest method which takes two parameters one map parameter, and the other is a String variable
#POST
public returnValue postMethod( Map<String,String> anotherMap,
#QueryParam("name") String name
) {}
It is easy to pass each parameter by itself where
the map parameter can be passed using XML as follow :
ClientResponse response = service
.type(MediaType.APPLICATION_XML)
.accept(MediaType.APPLICATION_XML)
.post(ClientResponse.class, map).getEntity(ClientResponse.class).
and the QueryParam can be passed as usual :
service.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
.accept(MediaType.APPLICATION_JSON_TYPE)
.post(ClientResponse.class, f)
where f is a Form ,
the question is : how can we pass both parameter together from the same Java client ?
So you're asking - how do I POST a Map and pass a String as a query param? With sending and receiving XML.
Here's how I'd do it:
ClientBuilder clientBuilder = ClientBuilder.newBuilder();
//Do some building code
Client client = clientBuilder.build();
WebTarget target = client.target(endPoint);
Response response = target
.queryParam("name", "value")
.request(MediaType.APPLICATION_XML_TYPE)
.post(Entity.entity(map), MediaType.APPLICATION_XML_TYPE);
Hope this helps.

How to get STRING response from RestTemplate postForLocation?

I'm creating a REST Client in Java with RestTemplate from Spring Framework.
Everything is fine until i have to do a post with postForLocation.
The webservice i'm having access return a json with informations about the POST ACTION.
In PHP it's fine but i really don't understand how to do in Java with RestTemplate.
public String doLogin()
{
Map<String, String> args = new HashMap<String, String>();
args.put("email", AUTH_USER);
args.put("token", AUTH_PASS);
String result = restTemplate.postForLocation(API_URL + "account/authenticate/?email={email}&token={token}", String.class, args);
return result;
}
This returns NULL.
With same code but using getForObject (and of course, changing the URL to something right) I have a full response, i.e. this works:
String result = restTemplate.getForObject(url, String.class);
So... how get the RESPONSE from a postForLocation?
Obs.: Sorry if this question is dumb. I'm beginner in Java
The postForLocation method returns the value for the Location header. You should use postForObject with the String class, which returns the server's response.
So like this:
String result = restTemplate.postForObject(API_URL + "account/authenticate/?email={email}&token={token}", String.class, args);
This will return the response as a string.
Thanks to one of answers i've figured out how get the response from a POST with Spring by using the postForObject
String result = restTemplate.postForObject(API_URL + "account/authenticate/?email="+ AUTH_USER +"&token="+ AUTH_PASS, null, String.class);
For some reason i can't use arguments with MAP and have to put them inline in URL. But that's fine for me.

Categories

Resources