I have the following code which works with jersey 1.x. However, I need to make it work with jersey 2.x and I noticed that a lot of the jersey classes and methods changed from one version to another. Any idea?
Client client = null;
try {
URLConnectionClientHandler ch = new URLConnectionClientHandler(new ProxyConnectionFactory(proxyHost, proxyPort));
client = new Client(ch);
WebResource webResource = client.resource(url);
ClientResponse response = ((Builder) webResource.type("application/json").header(authKey, authCreds)).post(ClientResponse.class, input);
String output = (String) response.getEntity(String.class);
System.out.println(output);
if (response.getStatus() != 200) {
System.out.println("Status Failed, Status: " + response.getStatus());
}
else {
System.out.println("Connection Successful!");
//additional code
}
} catch (Exception e) {
System.out.println("Exception occurred");
} finally {
client.destroy();
}
In this code snippet, ProxyConnectionFactory is a class which sets the proxy configuration. It implements HttpURLConnectionFactory which is also a jersey 1.x interface.
The basic type analogs would be as follows:
Clientjavax.ws.rs.client.ClientWebResourcejavax.ws.rs.client.WebTargetClientResponsejavax.ws.rs.core.ResponseTo build the client, you generally use one of the
ClientBuilderstatic builder methods. The most basic one to use would be thenewClient()method, which returns a new instance of theClientIf you need to configure the client, you can do so in multiple ways. For instance, if you need to register some properties or providers, you can:
Configure while building:
Use a
ClientConfig:Configure the client directly
Once you have a
Client, you want to get aWebTarget. You would do that by providing a URI to theClient#target()method.If you need to do anything to the URI like add a path, query param, or matrix param, you would do so on the
WebTarget. Otherwise you would now call theWebTarget#request()method to get anInvocation.BuilderWith the
Invocation.Builder, you can add headers and finally make the request. You don't have to assign any new variable to theInvocation.Builder(or even theWebTargetfor that matter). I did so for demonstrative purposes. You can continue to chain the method calls. For exampleFinally to make the request, you would use one of the HTTP methods of the
Invocation.Builder. In your case it would be thepost()method. You can pass anEntityto this method and the result would be aResponseTo read the response, you use
Response#readEntity(Class)If you have a POJO class you want the response to be deserialized to then pass that class to the
readEntity()method. You will need to have a provider for whatever data type is expected. For example if it is JSON to be converted to a POJO, then you'll want to have the Jackson provider:Proxies
As far as the proxy goes, Jersey has some properties you can set
ClientProperties.PROXI_URISee also