下面是在 Java 中访问 RESTful 服务的几个编程选项。
使用 JDK/JRE API
下面是使用 JDK/JRE 中的 API 调用 RESTful 服务的示例
String uri =
"http://localhost:8080/CustomerService/rest/customers/1";
URL url = new URL(uri);
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");
JAXBContext jc = JAXBContext.newInstance(Customer.class);
InputStream xml = connection.getInputStream();
Customer customer =
(Customer) jc.createUnmarshaller().unmarshal(xml);
connection.disconnect();
使用 Jersey API
大多数 JAX-RS 实现都包含使访问 RESTful 服务更容易的 API。客户端 API 包含在 JAX-RS 2 规范中。
import java.util.List;
import javax.ws.rs.core.MediaType;
import org.example.Customer;
import com.sun.jersey.api.client.*;
public class JerseyClient {
public static void main(String[] args) {
Client client = Client.create();
WebResource resource = client.resource("http://localhost:8080/CustomerService/rest/customers");
// Get response as String
String string = resource.path("1")
.accept(MediaType.APPLICATION_XML)
.get(String.class);
System.out.println(string);
// Get response as Customer
Customer customer = resource.path("1")
.accept(MediaType.APPLICATION_XML)
.get(Customer.class);
System.out.println(customer.getLastName() + ", "+ customer.getFirstName());
// Get response as List<Customer>
List<Customer> customers = resource.path("findCustomersByCity/Any%20Town")
.accept(MediaType.APPLICATION_XML)
.get(new GenericType<List<Customer>>(){});
System.out.println(customers.size());
}
}
了解更多信息