Jersey - 如何在 REST API 响应中设置 Cookie

位置:首页>文章>详情   分类: Java教程 > 编程技术   阅读(339)   2023-06-26 07:54:18

在此示例中,我们将学习将 cookie 设置为 Jersey REST API 发送的 HTTP 响应。此示例使用 javax.ws.rs.core.Response 将 cookie 设置为发送给 REST 客户端的 REST 响应。

设置 Cookie 语法

要在 REST API 响应中设置 cookie,请获取 Response 引用并使用它的 cookie() 方法。

Response.ok().entity(list).cookie(new NewCookie("cookieResponse", "cookieValueInReturn")).build();

休息 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]]

快乐学习!!

标签2: Jersey
地址:https://www.cundage.com/article/jersey-how-to-set-cookie-in-rest-api-response.html

相关阅读

在 Jersey ExceptionMapper 示例中,我们将学习使用 ExceptionMapper 接口,同时开发 Jersey RESTful Web 服务。出于演示目的,我正在修改为球...
学习使用 Spring Boot 和 Jersey 框架配置和创建 JAX-RS 2.0 REST API。此示例应用程序使用 Jersey 的 ServletContainer 来部署 RES...
在本例中,我们将学习将 cookie 设置到 Jersey 客户端调用的 HTTP 请求中。此示例使用 Invocation.Builder 将 cookie 设置为传出 REST 调用。 设置...
默认情况下,Jersey 使用 JUL 进行日志记录——并且不会在日志中打印请求/响应实体主体。要打印实体内容,您必须创建自己的 LoggingFiler,并将其注册以代替默认的 org.gla...
在此Jersey rest 安全示例中,我们将学习使用基本身份验证保护Jersey REST API。这将强制每个用户提供用户名/密码以对门户进行身份验证。此外,用户还必须具有一定级别的角色。我...
在此示例中,我们将学习将 cookie 设置为 Jersey REST API 发送的 HTTP 响应。此示例使用 javax.ws.rs.core.Response 将 cookie 设置为发...
默认情况下,在 JAX-RS 中,@Path 注释中指定的所有 URL 都是CASE-SENSITIVE。在本教程中,我给出了一个简单的 CASE-INSENSITIVE URL 示例,可以在任...
本教程解释了如何将 google Gson 与 Jersey 2.x 结合使用。还有一些其他的 java 库也能够进行这种转换,例如MOXy、杰克逊或JSONP;但是 Gson 是极少数不需要任...
如果您已经开始使用 Jersey,那么在配置它时可能会遇到这个问题。这是项目对运行时依赖不足的结果。 tomcat服务器很可能会遇到这个问题。 随机异常 错误 错误日志将如下所示。 SEVERE...
在此Jersey 2 文件上传示例中,我们将学习使用 Jersey 的多部分表单数据支持上传二进制文件(例如本示例中的 PDF 文件) &gtl;。我们将在下面了解完成功能所需的更改。 1. J...