原文: https://howtodoinjava.com/jersey/jersey-client-cookie-example/

在本示例中,我们将学习在 Jersey 客户端发起的 HTTP 请求中设置 cookie。 本示例利用Invocation.Builder将 Cookie 设置为外发 REST 调用。

设置 Cookie 示例

要在 REST API 请求中设置 Cookie,请先从webTarget.request()方法中获取Invocation.Builder的引用,然后再使用它的方法。

  1. Client client = ClientBuilder.newClient( new ClientConfig().register( LoggingFilter.class ) );
  2. WebTarget webTarget = client.target("http://localhost:8080/JerseyDemos/rest").path("employees");
  3. Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
  4. Response response = invocationBuilder
  5. .cookie("cookieParam1","cookieValue1")
  6. .cookie(new Cookie("cookieParam2", "cookieValue2"))
  7. .get();
  8. Employees employees = response.readEntity(Employees.class);
  9. //More code

REST API 代码

我在下面编写了 REST API 进行测试。

  1. @GET
  2. @Produces(MediaType.APPLICATION_JSON)
  3. @Consumes(MediaType.APPLICATION_JSON)
  4. public Employees getAllEployees(@CookieParam(value="cookieParam1") String cookieParam1,
  5. @CookieParam(value="cookieParam2") String cookieParam2)
  6. {
  7. System.out.println("cookieParam1 is :: "+ cookieParam1);
  8. System.out.println("cookieParam2 is :: "+ cookieParam2);
  9. Employees list = new Employees();
  10. list.setEmployeeList(new ArrayList<Employee>());
  11. list.getEmployeeList().add(new Employee(1, "Lokesh Gupta"));
  12. list.getEmployeeList().add(new Employee(2, "Alex Kolenchiskey"));
  13. list.getEmployeeList().add(new Employee(3, "David Kameron"));
  14. return list;
  15. }

演示

现在,按照第一个标题中的建议,使用 Jersey 客户端代码在 REST API 之上进行调用。

  1. public static void main(String[] args)
  2. {
  3. Client client = ClientBuilder.newClient( new ClientConfig().register( LoggingFilter.class ) );
  4. WebTarget webTarget = client.target("http://localhost:8080/JerseyDemos/rest").path("employees");
  5. Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
  6. Response response = invocationBuilder
  7. .cookie("cookieParam1","cookieValue1")
  8. .cookie(new Cookie("cookieParam2", "cookieValue2"))
  9. .get();
  10. Employees employees = response.readEntity(Employees.class);
  11. List<Employee> listOfEmployees = employees.getEmployeeList();
  12. System.out.println(response.getStatus());
  13. System.out.println(Arrays.toString( listOfEmployees.toArray(new Employee[listOfEmployees.size()]) ));
  14. }
  1. Output:
  2. On client side:
  3. Oct 01, 2015 4:53:59 PM org.glassfish.jersey.filter.LoggingFilter log
  4. INFO: 1 * Sending client request on thread main
  5. 1 > GET http://localhost:8080/JerseyDemos/rest/employees
  6. 1 > Accept: application/json
  7. 1 > Cookie: $Version=1;cookieParam1=cookieValue1,$Version=1;cookieParam2=cookieValue2
  8. On server side:
  9. cookieParam1 is :: cookieValue1
  10. cookieParam2 is :: cookieValue2

祝您学习愉快!