Is REST supported by default in JavaScript and Java or do I need to install new software?
Do I req开发者_高级运维uire to install new software to use REST services with JavaScript and Java?
You don't need anything beyond a web server. The basic point of REST is this:
- every "resource" has a URI (read "URL") address
- every resource can deal with the four basic HTTP methods: GET, PUT, POST, DELETE
So, let's say you have a customer record, and the record is identified with an ID number. You might have the customer be identified with a URL like
http://example.com/customer/124c41
A GET on that URL would give you the information for display; a PUT would update it; a POST would create it (most people actually use POST where formally you'd want PUT) and a DELETE deletes it.
It's you're responsibility to handle the exact implementation, but that's the model.
No, you do not. REST services that only use the GET and POST HTTP verbs can be accessed just like any URL in javascript. Most commonly, you'd use AJAX to access a REST service and do something with the response.
Another thing to consider is the client side.
You can use the standard Java SE APIs:
private void updateCustomer(Customer customer) {
try {
URL url = new URL("http://www.example.com/customers");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("PUT");
connection.setRequestProperty("Content-Type", "application/xml");
OutputStream os = connection.getOutputStream();
jaxbContext.createMarshaller().marshal(customer, os);
os.flush();
connection.getResponseCode();
connection.disconnect();
} catch(Exception e) {
throw new RuntimeException(e);
}
}
Or you can use the REST client APIs provided by JAX-RS implementations such as Jersey. These APIs are easier to use, but require additional jars on your class path.
WebResource resource = client.resource("http://www.example.com/customers");
ClientResponse response = resource.type("application/xml");).put(ClientResponse.class, "<customer>...</customer.");
System.out.println(response);
精彩评论