I have a basic FeingClient and I need to set a cookie in the request headers so that I have a valid response. I don't really know how to do this, I have tried with #Headers and #Header as well but no success. I need for the /dogs request to have the CUSTOM_TOKEN set like I see in Postman (Cookie: CUSTOM_COOKIE={VALUE})
#FeignClient(value = "petShopApi", url="http://localhost:8080/pets")
public interface PetShopFeignClient {
#GetMapping("/dogs")
Response getResponse(#CookieValue("CUSTOM_TOKEN") String token);
}
Related
I am trying to setup code in such as way that executes a POST request in my step definition class, and the POST request includes authorization (bearer token), content type, and Cookies in headers, as well as a request body in json format.
I have the bearer token process setup and am using the bearerToken for the authorization as header, content type is application/json, and the request body has the below structure:
I am unsure how to proceed in this way using Rest Assured. Below is a given method that sets the base uri and the bearer token based on environment, and based on that the bearer token will be used accordingly for authorization as header when executing the POST request:
#Given("Request the environment for the Master API {string}")
public void getMasterAPIBaseUrl(String region) throws JSONException {
if (region.equalsIgnoreCase("DEV")) {
bearerToken = accTokenSetup.accessTokenSetup(region);
RestAssured.baseURI = urlProps.getProperty("devMasterAPIUrl");
}
else if (region.equalsIgnoreCase("STG")) {
bearerToken = accTokenSetup.accessTokenSetup(region);
RestAssured.baseURI = urlProps.getProperty("stgMasterAPIUrl");
}
Reporter.log("Getting master api base url for the environment which is " + RestAssured.baseURI, true);
}
Now I need an #When step that will execute the mentioned POST request with the request body and the headers (authorization, content-type, and Cookies). I know what is required would be the endpoint, headers, request body, etc. but unsure of how to proceed with it. Any help would be appreciated!
I have issue in my application. I have various REST enpoints which are working fine. But now I want to send POST request with body. I already have 2 endpoints for POST method, but data are send using PathParam.
I created new endpoint, but when I send request I am getting CORS error. When I use the same endpoint without body in request everything is okay but of course at backend side I do not get any data from frontend (I have breakpoint inside method).
this is how I send request from my angular application:
post(requestUrl: string, body?: any): Observable<any> {
return this.httpClient.post<any>(this.API_URL + requestUrl, {password: 'test'});
}
After sending request I got:
Access to XMLHttpRequest at 'http://localhost:8080/...' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
If I send request like this (without body) this endpoint works fine:
post(requestUrl: string, body?: any): Observable<any> {
return this.httpClient.post<any>(this.API_URL + requestUrl);
}
At backend side I have added settings for CORS:
return Response.ok(object).header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
.allow("OPTIONS").build();
When I am sending request from Insomnia everything is ok - I can send body and I am getting sent data on backend.
Should I somehow set request headers at frontend side?
Here is my AdminApiController class:
#Path("/admin")
#RequestScoped
public class AdminApiController extends BaseApiController {
#Inject
private AdminAssembler adminAssembler;
#POST
#Path("/login")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response login(LoginRequest request) {
return Response.ok(adminAssembler.login(request))
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
.header("Access-Control-Allow-Headers", "Content-Type")
.allow("OPTIONS").build();
}
}
When your angular application sends a JSON payload in a POST request, it probably adds the header Content-Type: application/json. This header classifies the POST request as a "non-simple" request (that is, a request that cannot result out of an HTML <form> element without additional Javascript). Such "non-simple" requests cause to browser to make a preceding preflight request, that is an OPTIONS request with headers
Origin: http://localhost:4200
Access-Control-Request-Method: POST
Access-Control-Request-Headers: Content-Type
to which the server must respond with an Access-Control-Allow-Origin header and Access-Control-Allow-Headers: Content-Type. If it does not, the browser will not make the POST request and show an error like you observed.
Your Java code covers only #POST, not #OPTIONS, that's why the server does not respond to the preflight request with the necessary headers. How best to handle the OPTIONS requests for all endpoints on your server is a question for Java experts (which I am not).
You need to define your httpOptions.
Try this.
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
post(requestUrl: string, body?: any): Observable<any> {
this.httpClient.post<any>(this.API_URL + requestUrl, {password: 'test'}, this.httpOptions)
}
Let me know if it worked for you.
I'm new to the java rest CXF client. I will make various requests to a remote server, but first I need to create a Ticket Granting Ticket (TGT). I looked through various sources but I could not find a solution. The server requests that I will create a TGT are as follows:
Content-Type: text as parameter, application / x-www-form-urlencoded as value
username
password
I create TGT when I make this request with the example URL like below using Postman. (URL is example). But in the code below, I'm sending the request, but the response is null. Could you help me with the solution?
The example URL that I make a request with POST method using Postman: https://test.service.com/v1/tickets?format=text&username=user&password=pass
List<Object> providers = new ArrayList<Object>();
providers.add(new JacksonJsonProvider());
WebClient client = WebClient.create("https://test.service.com/v1/tickets?format=text&username=user&password=pass", providers);
Response response = client.getResponse();
You need to do a POST, yet you did not specify what your payload looks like?
Your RequestDTO and ResponseDTO have to have getters/setters.
An example of using JAX-RS 2.0 Client.
Client client = ClientBuilder.newBuilder().register(new JacksonJsonProvider()).build();
WebTarget target = client.target("https://test.service.com/v1/tickets");
target.queryParam("format", "text");
target.queryParam("username", "username");
target.queryParam("password", "password");
Response response = target.request().accept(MediaType.APPLICATION_FORM_URLENCODED).post(Entity.entity(yourPostDTO,
MediaType.APPLICATION_JSON));
YourResponseDTO responseDTO = response.readEntity(YourResponseDTO.class);
int status = response.getStatus();
Also something else that can help is if you copy the POST request from POSTMAN as cURL request. It might help to see the differences between your request and POSTMAN. Perhaps extra/different headers are added by postman?
Documentation: https://cxf.apache.org/docs/jax-rs-client-api.html#JAX-RSClientAPI-JAX-RS2.0andCXFspecificAPI
Similar Stackoverflow: Is there a way to configure the ClientBuilder POST request that would enable it to receive both a return code AND a JSON object?
I found two classes in JAX-RS API javax.ws.rs.core.Cookie and javax.ws.rs.core.NewCookie. What are the advantages of one over another?
I would like to know Which one is recommended to use and when?
Thanks in advance :)
It's not about recommended, it's about appropriate. One is for a request, and one is for a response. You can see the two different javadocs.
Cookie
Represents the value of a HTTP cookie, transferred in a request.
NewCookie
Used to create a new HTTP cookie, transferred in a response.
NewCookie, when sent in the Response, will set a Set-Cookie response header with the cookie information, and Cookie will set the Cookie request header with the cookie information. This is per the HTTP spec.
Example usage:
#GET
public Response get() {
return Response.ok("blah")
.cookie(new NewCookie("foo-cookie", "StAcKoVeRfLoW2020"))
.build();
}
[..]
Client client = ClientBuilder.newClient();
Response response = client
.target("https://cookieurl.com/api/some-resource")
.request()
.cookie(new Cookie("foo-cookie", "StAcKoVeRfLoW2020"))
.get();
#Path("some-resource")
public class SomeResource {
#POST
public Response post(#CookieParam("foo-cookie") Cookie cookie) {
}
}
Normally on the client side, you wouldn't manually create the Cookie as I did. Most of time you would get the cookies from the response of an initial request, then send those cookies back. This means that in the Response, you will have NewCookies and you you need to turn those into Cookies for the next request. This can easily be accomplished by calling newCookie.toCookie()
Map<String, NewCookie> cookies = response.getCookies();
Invocation.Builder ib = target.request();
for (NewCookie cookie: cookies.values()) {
ib.cookie(cookie.toCookie());
}
Response response = ib.get();
I am consuming a third party webservice using AXIS2 stub. The primary method which I use works FINE and has below signature:
boolean isValidUser(username, password);
The webservice is supposed to return a String (token) in the response headers as cookie :- WSToken
But I cannot find ANY method to extract the headers and cookies from the response. In fact there is no HTTPResponse object to fetch the cookies !.
I have tried this code:
MessageContext context = stub._getServiceClient().getLastOperationContext().getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
Object response = context.getProperty("response");
But it returns a null value as there is no such property in the context. The context has below properties:
transport.http.statusCode
CHARACTER_SET_ENCODING
TRANSPORT_HEADERS
org.apache.axiom.om.util.DetachableInputStream
messageType
ContentType
TRANSPORT_IN
How can I get the cookie called 'WSToken' from the response using the stub ?
The TRANSPORT_HEADERS property should give you the HTTP headers you got. You can then look for Set-Cookie headers.