JAXRS Rest Client

From JavaWiki.org
Jump to: navigation, search

Option 1 : Using interface proxy

import javax.ws.rs.FormParam;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;

import org.apache.cxf.jaxrs.client.JAXRSClientFactory;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;

public class RestClient {
	public static void main(String[] args) {
		final MyApiClient client = JAXRSClientFactory.create("http://localhost:8080/api", MyApiClient.class);

		final HTTPClientPolicy clientPolicy = WebClient.getConfig(client).getHttpConduit().getClient();
		clientPolicy.setConnectionTimeout(15 * 1000);
		clientPolicy.setReceiveTimeout(15 * 1000);

		final Response response = client.hello("your-authorization-token", "javawiki");
		System.out.println("Response Status: " + response.getStatus());
	}
}

@Path("/testapi")
public interface MyApiClient {
	@PUT
	@Path("/hello")
	Response hello(@HeaderParam("AUTHORIZATION") String authorization, @FormParam("name") String name);
}

Option 2: Direct client

import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.Response;

public class RestClient {
	public static void main(String[] args) {
		final Client client = ClientBuilder.newClient();

		client.property("http.connection.timeout", 15 * 1000); // milliseconds
		client.property("http.receive.timeout", 10 * 1000); // milliseconds

		final WebTarget target = client.target("http://localhost:8080/api/testapi/hello"); 
		final Response response = target.request(MediaType.APPLICATION_JSON_TYPE)
			.header("AUTHORIZATION", authorization)
			.put(Entity.form(new Form().param("name", "javawiki)));
		System.out.println("Response: " + response.getStatus());

 
		client.close();
	}
}