如何在使用 Java Jersey 客户端发送请求时启用 cookie?

How to enable cookies while sending a request with Java Jersey client?

我需要向 API 发送获取请求并获取结果。我在我的项目中使用 Java,Jersey 库,我决定使用 Jersey 客户端来获取数据。但是,API returns 一条错误消息表明我应该启用 cookie 来访问此 API。当尝试使用像邮递员这样的应用程序时,或者使用像 chrome 这样的普通浏览器时,我可以获得正确的响应。但是我找不到如何在 Java Jersey 客户端对象中启用 cookie。

我搜索了解如何在 Java Jersey 客户端中启用 cookie,但找不到任何相关资源。所以我无法尝试任何解决方案。

我的代码很简单:

    Client client = Client.create(); // Create jerseu client
    WebResource webResource = client.resource(BASEURI +  EXCHANGEINFO); // create web resource with a specific URI

    System.out.println(webResource 
            .accept("application/json")
            .get(ClientResponse.class)
            .getEntity(String.class)); // Write results to console

在这个请求的结果中,我得到了上面提到的错误。如何在使用 Java Jersey 客户端发送请求时启用 cookie?

根据讨论,我已经完成了您提供的 api。实际上,api 在进行 rest 调用时提供了误导性消息。如果您查看从 api 调用收到的错误消息的详细信息,它说。

The owner of this website (api.pro.coinbase.com) has banned your access based on your browser's signature (4e0a3c06895d89af-ua21).

那么答案是什么? api 实际上希望从浏览器进行调用,每个浏览器发送一个名为 "User-Agent" 的 header。看看什么是user agent。不过,我已经解决了你的问题,你可以查看下面的完整代码。

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class TestGetCallByJersey {
  public static void main(String[] args) {
    String resourceUri = "https://api.pro.coinbase.com/products";
    try {
      Client client = Client.create();
      WebResource webResource = client.resource(resourceUri);
      ClientResponse response =
          webResource
              .accept("application/json")
              .header("User-Agent", "Mozilla/5.0")
              .get(ClientResponse.class);

      System.out.println("response status = " + response.getStatus());
      String result = response.getEntity(String.class);
      System.out.println("Output from api call .... \n" + result);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

目前,我已经在Java 8中进行了测试,我使用了以下jar文件。

jersey-client 版本 1.8 如果你正在使用 Maven,你可以在 pom.xml.

中包含以下依赖项
<dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-client</artifactId>
            <version>1.8</version>
        </dependency>