在本例中,我们将学习将 cookie 设置到 Jersey 客户端调用的 HTTP 请求中。此示例使用 Invocation.Builder
将 cookie 设置为传出 REST 调用。
要在 REST API 请求中设置 cookie,首先从 Invocation.Builder
方法获取 webTarget.request()
的引用,然后使用它的方法。
Client client = ClientBuilder.newClient( new ClientConfig().register( LoggingFilter.class ) ); WebTarget webTarget = client.target("http://localhost:8080/JerseyDemos/rest").path("employees"); Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON); Response response = invocationBuilder .cookie("cookieParam1","cookieValue1") .cookie(new Cookie("cookieParam2", "cookieValue2")) .get(); Employees employees = response.readEntity(Employees.class); //More code
为了测试目的,我在下面编写了 REST API。
@GET @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Employees getAllEployees(@CookieParam(value="cookieParam1") String cookieParam1, @CookieParam(value="cookieParam2") String cookieParam2) { System.out.println("cookieParam1 is :: "+ cookieParam1); System.out.println("cookieParam2 is :: "+ cookieParam2); Employees list = new Employees(); list.setEmployeeList(new ArrayList<Employee>()); list.getEmployeeList().add(new Employee(1, "Lokesh Gupta")); list.getEmployeeList().add(new Employee(2, "Alex Kolenchiskey")); list.getEmployeeList().add(new Employee(3, "David Kameron")); return list; }
现在让我们按照第一个标题中的建议使用 Jersey 客户端代码调用上面的 REST API。
public static void main(String[] args) { Client client = ClientBuilder.newClient( new ClientConfig().register( LoggingFilter.class ) ); WebTarget webTarget = client.target("http://localhost:8080/JerseyDemos/rest").path("employees"); Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON); Response response = invocationBuilder .cookie("cookieParam1","cookieValue1") .cookie(new Cookie("cookieParam2", "cookieValue2")) .get(); Employees employees = response.readEntity(Employees.class); List<Employee> listOfEmployees = employees.getEmployeeList(); System.out.println(response.getStatus()); System.out.println(Arrays.toString( listOfEmployees.toArray(new Employee[listOfEmployees.size()]) )); }
Output: On client side: Oct 01, 2015 4:53:59 PM org.glassfish.jersey.filter.LoggingFilter log INFO: 1 * Sending client request on thread main 1 > GET http://localhost:8080/JerseyDemos/rest/employees 1 > Accept: application/json 1 > Cookie: $Version=1;cookieParam1=cookieValue1,$Version=1;cookieParam2=cookieValue2 On server side: cookieParam1 is :: cookieValue1 cookieParam2 is :: cookieValue2
快乐学习!!
标签2: Jersey地址:https://www.cundage.com/article/jersey-client-cookie-example.html