原文: https://howtodoinjava.com/jersey/jersey-how-to-set-cookie-in-rest-api-response/
在此示例中,我们将学习为 Jersey REST API 发送的 HTTP 响应设置 cookie。 本示例利用javax.ws.rs.core.Response
将 Cookie 设置为发送到 REST 客户端的 REST 响应中。
设置 Cookie 语法
要在 REST API 响应中设置 Cookie,请获取Response
参考并使用其cookie()
方法。
Response.ok().entity(list).cookie(new NewCookie("cookieResponse", "cookieValueInReturn")).build();
Rest API 示例代码
我在下面编写了 REST API 进行测试。
@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response getAllEployees()
{
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 Response.ok().entity(list).cookie(new NewCookie("cookieResponse", "cookieValueInReturn")).build();
}
演示
现在,使用 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.get();
Employees employees = response.readEntity(Employees.class);
List<Employee> listOfEmployees = employees.getEmployeeList();
System.out.println(response.getCookies());
System.out.println(response.getStatus());
System.out.println(Arrays.toString( listOfEmployees.toArray(new Employee[listOfEmployees.size()]) ));
}
Output:
{cookieResponse=cookieResponse=cookieValueInReturn;Version=1}
200
[Employee [id=1, name=Lokesh Gupta], Employee [id=2, name=Alex Kolenchiskey], Employee [id=3, name=David Kameron]]
祝您学习愉快!