# Jersey 客户端 - 设置 Cookie 示例

> 原文： [https://howtodoinjava.com/jersey/jersey-client-cookie-example/](https://howtodoinjava.com/jersey/jersey-client-cookie-example/)

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

## 设置 Cookie 示例

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

```java
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 代码

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

```java
@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 之上进行调用。

```java
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()]) ));
}

```

```java
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
```

**祝您学习愉快！**