I have a Jersey REST client talking to (or at least attempting to talk) with PagerDuty (a RESTful https service). I have my client configured for SSL at that seems to be doing it's stuff correctly. But when I tried to connect and access a URI, I get the message: Error reading entity from input stream which I presume is on my end, not PagerDuty's.
Here is my code:
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());
}
}
}
Any idea what's going on. Perhaps the SSL is screwed up and that's the cause of the problem? In any event, I've put an arrow at the line that generated the exception. Any help will be most definitely be very appreciated.
Thanks, Rob
Your problem might be that you are trying to get an instance of ClientResponse
, which is incorrect. With Jersey-/JAX-RS- 2.x, you should instead be using Response
at the return type
Response response = builder.accept("application/json").get();
If you want to read the entity, you would use
MyPojo pojo = response.readEntity(MyPojo.class);
If you don't need any information from the Response
, then you could simply do this
MyPojo pojo = builder.accept(...).get(MyPojo.class);
Another thing, for JSON to POJO and vice-versa, make sure you have a JSON Provider, such as this one
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey2.version}</version>
</dependency>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With