java rest client for mixed parameter forms - java

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.

Related

Get Cookie By name after a restTemplate call

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 ?

How to write Mock test cases for Webtarget and Response for a rest client?

WebTarget resource = clientLocal.target(/test/url))
Response response = resource.request(MediaType.APPLICATION_JSON)
.header("Content-type", MediaType.APPLICATION_JSON)
.header("Authorization", "Basic"+" "+"234YML")
.post(Entity.entity("", MediaType.TEXT_PLAIN), Response.class);
responseEntity = response.readEntity(Test.class);
When Response object is mocked, builder object for Authorization header is returning null,
Mockito.when(mockWebTarget.request(MediaType.APPLICATION_JSON)).thenReturn(mockBuilder);
Mockito.when(mockBuilder.header("Content-type", MediaType.APPLICATION_JSON))
.thenReturn(mockBuilder);
Mockito.when(mockBuilder.header("Authorization",eq(anyString())))
.thenReturn(mockBuilder);
Mockito.when(mockBuilder.post(Entity.entity(anyString(), MediaType.TEXT_PLAIN), eq(Response.class)))
.thenReturn(mockResponse);
How the second part of header should be mocked so that it does not return null value?
eq(anyString()) is the problem in
Mockito.when(mockBuilder.header("Authorization",eq(anyString())))
.thenReturn(mockBuilder);
It should be
Mockito.when(mockBuilder.header(eq("Authorization"), anyString()))
.thenReturn(mockBuilder);
The argument matcher eq is used for literal matches.
Also if you are using argument matchers, all arguments have to be provided by matchers.
The first one worked because all the arguments were literal values.
That would also mean that
Mockito.when(mockBuilder.post(Entity.entity(anyString(), MediaType.TEXT_PLAIN), eq(Response.class)))
.thenReturn(mockResponse);
needs to change to
Mockito.when(mockBuilder.post(any(Entity.class), eq(Response.class)))
.thenReturn(mockResponse);

how to get the value from HttpMethodParams

At client side I use the following code:
HashMap<String, String> paramMap = new HashMap<>();
paramMap.put("userId", "1579533296");
paramMap.put("identity", "352225199101195515");
paramMap.put("phoneNum", "15959177178");
HttpClient client = new HttpClient();
PostMethod method = new PostMethod("http://localhost:8088/requestTest");
HttpMethodParams p = new HttpMethodParams();
for (Map.Entry<String, String> entry : paramMap.entrySet()) {
p.setParameter(entry.getKey(), entry.getValue());
}
method.setParams(p);
client.executeMethod(method);
And the code of my server-side is like this:
#RequestMapping("/requestTest")
public void requestTest(HttpServletRequest request) throws IOException {
String userId = request.getParameter("userId");
String identity= request.getParameter("identity");
String phoneNum= request.getParameter("phoneNum");
System.out.println(userId+identity+phoneNum);
}
but I got the null value of userId,identity,and phoneNum,so how can I get the value of them? I know I can use method.setParameter(key,value) to set the parameter at client-side and use getParameter(key) to get the parameter value, but I just curious if there any way to get the value at server-side set by HttpMethodParams.
I think , you are getting confused between user defined parameters set in HttpServletRequest and HttpMethodParams .
As per JavaDoc of - HttpMethodParams ,
This class represents a collection of HTTP protocol parameters
applicable to HTTP methods.
These are predefined parameters specific to that HTTP method (see this)and has nothing to do with - HttpServletRequest parameters.
Request parameters need to be set as illustrated here
You have to also note that all these classes (HttpClient, PostMethod, HttpMethodParams etc ) that you are using on client side are from Apache to just be a convenient way to generate and call a HTTP end point but eventually what you will have on server side is a HttpServletRequest and there system is not Apache HttpClient specific.
So all you got on server side is to extract a named header or headers using - getHeaders() , getIntHeader() , getHeaderNames() , getDateHeader() , getProtocol() etc . Server side is standardized so you shouldn't see anything like - HttpMethodParams there.
You have to send your parameters using HttpServletRequest.
HttpMethodParams represent a collection of HTTP protocol parameters applicable to HTTP methods. List of Http method parameter can be found here.
But if you want to send it forcibly by HttpMethodParams you can set the JSON representation of your parameter in one of the variables of HttpMethodParameter and retrieve its value using that variable name.
Sample Code:
HttpMethodParams p = new HttpMethodParams();
p.setCredentialCharset("{userId":1579533296}");
//for loop not required
//your code
Now you can parse that JSON using ObjectMapper and get your required value.
Sample Code:
HttpMethodParams p = new HttpMethodParams();
JSONObject jsonObj = new JSONObject(p.getCredentialCharset());
jsonObj.get("userdId");
Note: This may work but not the recommended way.

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