你可以做你的客戶端代碼類似:
private static final String URI = "http://localhost/rest/customer";
private Customer readCustomer(String id) {
try {
URL url = new URL(URI + "/" + id);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");
InputStream data = connection.getInputStream();
// TODO - Read data from InputStream
connection.disconnect();
return customer;
} catch(Exception e) {
throw new RuntimeException(e);
}
}
private void createCustomer(Customer customer) {
try {
URL url = new URL(URI);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/xml");
OutputStream os = connection.getOutputStream();
// TODO - Write data to OutputStream
os.flush();
connection.getResponseCode();
connection.disconnect();
} catch(Exception e) {
throw new RuntimeException(e);
}
}
private void updateCustomer(Customer customer) {
try {
URL url = new URL(URI);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("PUT");
connection.setRequestProperty("Content-Type", "application/xml");
OutputStream os = connection.getOutputStream();
// TODO - Write data to OutputStream
os.flush();
connection.getResponseCode();
connection.disconnect();
} catch(Exception e) {
throw new RuntimeException(e);
}
}
private void deleteCustomer(String id) {
try {
URL url = new URL(URI + "/" + id);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("DELETE");
connection.getResponseCode();
connection.disconnect();
} catch(Exception e) {
throw new RuntimeException(e);
}
}