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

我需要向 API 发送获取请求并获取结果。我在我的项目中使用 Java,Jersey 库,我决定使用 Jersey 客户端来获取数据。但是,该 API 返回一条错误消息,表明我应该启用 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?


慕无忌1623718
浏览 66回答 1
1回答

慕桂英3389331

根据讨论,我已经浏览了您提供的 API。实际上,api 在进行 rest 调用时提供了误导性消息。如果您查看从 api 调用收到的错误消息的详细信息,它说。本网站 (api.pro.coinbase.com) 的所有者已根据您浏览器的签名 (4e0a3c06895d89af-ua21) 禁止您访问。所以答案是什么 ?api 实际上希望调用应该从浏览器进行,并且每个浏览器都会发送一个名为“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 {&nbsp; public static void main(String[] args) {&nbsp; &nbsp; String resourceUri = "https://api.pro.coinbase.com/products";&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; Client client = Client.create();&nbsp; &nbsp; &nbsp; WebResource webResource = client.resource(resourceUri);&nbsp; &nbsp; &nbsp; ClientResponse response =&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; webResource&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .accept("application/json")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .header("User-Agent", "Mozilla/5.0")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .get(ClientResponse.class);&nbsp; &nbsp; &nbsp; System.out.println("response status = " + response.getStatus());&nbsp; &nbsp; &nbsp; String result = response.getEntity(String.class);&nbsp; &nbsp; &nbsp; System.out.println("Output from api call .... \n" + result);&nbsp; &nbsp; } catch (Exception e) {&nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; }&nbsp; }}目前,我已经在 Java 8 中进行了测试,并使用了以下 jar 文件。jersey-client 版本 1.8 如果你使用 Maven,你可以在 pom.xml 中包含以下依赖项。<dependency>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <groupId>com.sun.jersey</groupId>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <artifactId>jersey-client</artifactId>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <version>1.8</version>&nbsp; &nbsp; &nbsp; &nbsp; </dependency>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java