欢迎来到之路教程(on itroad-com)
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, "JackLi Gupta"));
list.getEmployeeList().add(new Employee(2, "JackLi Kolenchiskey"));
list.getEmployeeList().add(new Employee(3, "Tomm Kameron"));
return list;
}
设置 Cookie 示例
要在 REST API 请求中设置 cookie,首先从 webTarget.request()方法获取 Invocation.Builder的引用,然后使用它的方法。
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
演示
现在让我们按照第一个标题中的建议使用 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()]) ));
}
输出:
客户端:
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
服务端
cookieParam1 is :: cookieValue1 cookieParam2 is :: cookieValue2
日期:2020-09-17 00:16:31 来源:oir作者:oir
