java - Jersey 客户端 REST API 生成 http 403 错误

标签 java jersey-client

我的 Java 项目上的泽西客户端 REST-API 生成 HTTP 403 错误。尽管这个项目运行良好,可以调用其他 Restful API,但基于假在线的 REST API JSONPlaceholder 除外。请找到我的以下代码:

public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub
    Client client = Client.create();
    WebResource webResource =   client.resource("http://jsonplaceholder.typicode.com/posts");
    ClientResponse response = webResource.accept("application/json")
            .get(ClientResponse.class);
    if(response.getStatus() != 200) {
        throw new RuntimeException("Failed http error code :" + response.getStatus());
    }
    String output = response.getEntity(String.class);
    System.out.println(output);

错误:

Click this link to see error !

最佳答案

正如我在评论中提到的,在 webResource 实例的 header 中设置键 ("user-agent") 和值 ("") 可以解决问题。希望以下代码片段能给您更好的想法。

Client client = Client.create();
WebResource webResource = client.resource("http://jsonplaceholder.typicode.com/posts");
ClientResponse response = webResource.accept("application/json")
            .header("user-agent", "")
            .get(ClientResponse.class);
if(response.getStatus() != 200) {
    throw new RuntimeException("Failed http error code :" + response.getStatus());
}
String output = response.getEntity(String.class);
System.out.println(output);

感谢大家的宝贵反馈。

关于java - Jersey 客户端 REST API 生成 http 403 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41043958/

相关文章:

jersey - 在 Dropwizard 应用程序中将 http 客户端注册到 jersey 环境时无法解析符号ExternalServiceResource

java - 为什么 ServletContext#getRealPath ("/") 返回相对路径?

java - Google Guice 是否活跃?

java - Java8 thenCompose 和 thenComposeAsync 之间的区别

Java:找出哪个观察者正在监听

jax-rs - 如何使用 JAX-RS 2.0 客户端 API 发布原始数据

Java,最昂贵的语句?

java - 尝试使用 Jersey Client 下载文件时出现 HTTP 400 错误

jersey-2.0 - Jersey(2.10.4) 实体提供者选择算法对自定义提供者(MessageBodyWriter)的优先级较低,使其不被调用

java - Jersey2 客户端抛出 javax.ws.rs.NotFoundException