Create a REST client【转载】
Jersey contains a REST client library which can be used for testing or to build a real client in Java. The usage of this library is demonstrated in the following tutorial.
Create a new Java project com.vogella.jersey.first.client and add the Jersey JARs to the project and the project build path. Create the following test class.
package com.vogella.jersey.first;
import java.net.URI;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import org.glassfish.jersey.client.ClientConfig;
public class Test {
public static void main(String[] args) {
ClientConfig config = new ClientConfig();
Client client = ClientBuilder.newClient(config);
WebTarget target = client.target(getBaseURI());
String response = target.path("rest").
path("hello").
request().
accept(MediaType.TEXT_PLAIN).
get(Response.class)
.toString();
String plainAnswer =
target.path("rest").path("hello").request().accept(MediaType.TEXT_PLAIN).get(String.class);
String xmlAnswer =
target.path("rest").path("hello").request().accept(MediaType.TEXT_XML).get(String.class);
String htmlAnswer=
target.path("rest").path("hello").request().accept(MediaType.TEXT_HTML).get(String.class);
System.out.println(response);
System.out.println(plainAnswer);
System.out.println(xmlAnswer);
System.out.println(htmlAnswer);
}
private static URI getBaseURI() {
return UriBuilder.fromUri("http://localhost:8080/com.vogella.jersey.first").build();
}
}

浙公网安备 33010602011771号