I need to send a get request to an API and get the results. I am using Java, Jersey library in my project and I decided to use Jersey client in order to get the data. However, the API returns an error message which indicates that I should enable cookies to reach out this API. I can get correct response when try with applications like postman, or just with using a normal browser like chrome. But I could not find out how can I enable cookies in Java Jersey client object.
I searched to learn how to enable cookies in a Java Jersey client but I could not find any resource about it. So I could not try any solution.
My code is very simple:
Client client = Client.create(); // Create jerseu client
WebResource webResource = client.resource(BASEURI + EXCHANGEINFO); // create web resource with a specific URI
System.out.println(webResource
.accept("application/json")
.get(ClientResponse.class)
.getEntity(String.class)); // Write results to console
At the result of this request, I got the error that I mentioned above. How can I enable cookies while sending a request with Java Jersey client?
答案 0 :(得分:0)
您必须像这样使用。我为您提供有关jersey客户端和Cookie的简短代码段。
Client client = Client.create(); // Create jerseu client
WebTarget webTarget = client.target(BASEURI + EXCHANGEINFO);
Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
Response response = invocationBuilder
.cookie("cookie-name","cookie-value")
.cookie(new Cookie("cookieParam2", "cookieValue2"))
.get();