java – 获取错误:从输入流中读取实体时出错

我有一个Jersey REST客户端与PagerDuty(一个RESTful https服务)交谈(或至少试图说话).我的客户端配置为SSL,似乎正确地做了它的东西.但是当我尝试连接并访问URI时,我收到消息:从输入流中读取实体时出错,我认为这是在我的最终,而不是PagerDuty.

这是我的代码:

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;

import org.glassfish.jersey.client.ClientResponse;




public class Harvest {

    public static void main(String[] args) throws KeyManagementException, 
        NoSuchAlgorithmException, NullPointerException {

        SSLContext sslContext = SSLContext.getInstance("SSL");
        HostnameVerifier
           hostnameVerifier=HttpsURLConnection.getDefaultHostnameVerifier();

        SecureRandom random = new SecureRandom();
        byte bytes[] = new byte[20];
        random.nextBytes(bytes);

        sslContext.init(null, null, random);

        Client client = ClientBuilder.newBuilder()
                .sslContext(sslContext)
                .hostnameVerifier(hostnameVerifier)
                .build();


        WebTarget target = client.target("https://peakhosting.pagerduty.com/api/v1/schedules");
        Invocation.Builder builder;
        builder = target.request();
        builder.header("Authorization", "Token token=<secret>");
        builder.accept(MediaType.APPLICATION_JSON);  

-->     ClientResponse response = builder.accept("application/json").get(ClientResponse.class);
        System.out.println(response.getStatus());

        if (response.getStatus() != 200) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + response.getStatus());
        }


    }
}

知道发生了什么.也许SSL搞砸了,这就是问题的原因?无论如何,我在生成异常的行上放了一个箭头.绝对非常感谢任何帮助.

谢谢,

最佳答案
您的问题可能是您尝试获取ClientResponse的实例,这是不正确的.使用Jersey- / JAX-RS-2.x,您应该在返回类型中使用Response

Response response = builder.accept("application/json").get();

如果你想阅读实体,你会使用

MyPojo pojo = response.readEntity(MyPojo.class);

如果您不需要响应中的任何信息,那么您可以简单地执行此操作

MyPojo pojo = builder.accept(...).get(MyPojo.class);

另一件事,对于JSON到POJO,反之亦然,确保你有JSON Provider,例如this one

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>${jersey2.version}</version>
</dependency>

转载注明原文:java – 获取错误:从输入流中读取实体时出错 - 代码日志