RESTful Web服务 – 方法
正如我们所讨论的那样,RESTful Web服务会大量使用HTTP动词来确定对指定资源的操作。下表列出了HTTP动词的常见用法示例。
HTTP方法 | GET |
---|---|
URI | http://localhost:8080/UserManagement/rest/UserService/users |
操作 | 获得用户列表 |
操作类型 | 只读 |
HTTP方法 | GET |
---|---|
URI | http://localhost:8080/UserManagement/rest/UserService/users/1 |
操作 | 获得ID为1的用户 |
操作类型 | 只读 |
HTTP方法 | POST |
---|---|
URI | http://localhost:8080/UserManagement/rest/UserService/users/2 |
操作 | 插入ID为2的用户 |
操作类型 | 不幂等 |
HTTP方法 | PUT |
---|---|
URI | http://localhost:8080/UserManagement/rest/UserService/users/2 |
操作 | 更新ID为2的用户 |
操作类型 | N/A |
HTTP方法 | DELETE |
---|---|
URI | http://localhost:8080/UserManagement/rest/UserService/users/1 |
操作 | 删除ID为1的用户 |
操作类型 | 幂等 |
HTTP方法 | OPTIONS |
---|---|
URI | http://localhost:8080/UserManagement/rest/UserService/users |
操作 | 列出Web服务中支持的操作 |
操作类型 | 只读 |
HTTP方法 | HEAD |
---|---|
URI | http://localhost:8080/UserManagement/rest/UserService/users |
操作 | 仅返回HTTP头,不包括正文 |
操作类型 | 只读 |
以下是需要考虑的重要点:
- GET操作是只读且安全的。
-
PUT和DELETE操作是幂等的,这意味着无论调用这些操作多少次,其结果始终相同。
-
PUT和POST操作几乎是相同的,不同之处仅在于PUT操作是幂等的,而POST操作可能会导致不同的结果。
示例
让我们更新RESTful Web服务 – 第一个应用程序教程中创建的示例,创建一个可以执行CRUD(Create、Read、Update、Delete)操作的Web服务。为简单起见,我们使用文件I/O来代替数据库操作。
更新com.tutorialspoint包下的 UserService.java 、 User.java 、 UserDao.java 文件。
User.java
package com.tutorialspoint;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "user")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
private String profession;
public User(){}
public User(int id, String name, String profession){
this.id = id;
this.name = name;
this.profession = profession;
}
public int getId() {
return id;
}
@XmlElement
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
@XmlElement
public void setName(String name) {
this.name = name;
}
public String getProfession() {
return profession;
}
@XmlElement
public void setProfession(String profession) {
this.profession = profession;
}
@Override
public boolean equals(Object object){
if(object == null){
return false;
}else if(!(object instanceof User)){
return false;
}else {
User user = (User)object;
if(id == user.getId()
&& name.equals(user.getName())
&& profession.equals(user.getProfession())
){
return true;
}
}
return false;
}
}
UserDao.java
将计算机领域的英文文章翻译成中文是一项有用的技能。上面这段HTML格式的代码讲述了一个Java程序,是一个用户类。该类有一个id,一个名字和一个职业,代表了一个用户的信息。此外,该类还有一些方法,例如getId()、getName()和getProfession(),它们可以获取相应的属性。此外,在equals()方法中还有一些逻辑来比较两个用户是否相等。
package com.tutorialspoint;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
public class UserDao {
// 获取所有用户列表
public List<User> getAllUsers(){
List<User> userList = null;
try {
File file = new File("Users.dat");
// 如果数据文件不存在,则添加初始用户并保存,否则读取保存的用户列表
if (!file.exists()) {
User user = new User(1, "Mahesh", "Teacher"); // 初始用户
userList = new ArrayList<User>();
userList.add(user);
saveUserList(userList);
}
else{
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
userList = (List<User>) ois.readObject(); // 读取保存的用户列表
ois.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return userList;
}
// 根据编号获取用户
public User getUser(int id){
List<User> users = getAllUsers();
for(User user: users){
if(user.getId() == id){
return user; // 返回匹配的用户
}
}
return null; // 没有匹配的用户返回 null
}
// 添加用户
public int addUser(User pUser){
List<User> userList = getAllUsers();
boolean userExists = false;
// 检查用户是否已存在
for(User user: userList){
if(user.getId() == pUser.getId()){
userExists = true;
break;
}
}
// 如果用户不存在,则添加该用户
if(!userExists){
userList.add(pUser);
saveUserList(userList);
return 1;
}
return 0;
}
// 更新用户
public int updateUser(User pUser){
List<User> userList = getAllUsers();
for(User user: userList){
if(user.getId() == pUser.getId()){
int index = userList.indexOf(user);
userList.set(index, pUser);
saveUserList(userList);
return 1;
}
}
return 0; // 如果没有匹配的用户,则更新失败
}
// 删除用户
public int deleteUser(int id){
List<User> userList = getAllUsers();
for(User user: userList){
if(user.getId() == id){
int index = userList.indexOf(user);
userList.remove(index);
saveUserList(userList);
return 1;
}
}
return 0; // 如果没有匹配的用户,则删除失败
}
// 保存用户列表到文件
private void saveUserList(List<User> userList){
try {
File file = new File("Users.dat");
FileOutputStream fos;
fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(userList); // 将用户列表保存到文件
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
UserService.java
package com.tutorialspoint;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
public class WebServiceTester {
private static final String BASE_URL = "http://localhost:8080/UserManagement/rest/UserService/";
public static void main(String[] args) {
try {
testGetAllUsers();
testGetUser();
testCreateUser();
testUpdateUser();
testDeleteUser();
testSupportedOperations();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void testGetAllUsers() throws IOException {
URL url = new URL(BASE_URL + "users");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/xml");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
}
private static void testGetUser() throws IOException {
URL url = new URL(BASE_URL + "users/1");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/xml");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
}
private static void testCreateUser() throws IOException {
URL url = new URL(BASE_URL + "users");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
String input = "id=5&name;=John&profession;=Tester";
conn.getOutputStream().write(input.getBytes());
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
}
private static void testUpdateUser() throws IOException {
URL url = new URL(BASE_URL + "users");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("PUT");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
String input = "id=5&name;=John&profession;=Developer";
conn.getOutputStream().write(input.getBytes());
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
}
private static void testDeleteUser() throws IOException {
URL url = new URL(BASE_URL + "users/5");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("DELETE");
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
}
private static void testSupportedOperations() throws IOException {
URL url = new URL(BASE_URL + "users");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("OPTIONS");
conn.setRequestProperty("Accept", "application/xml");
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
}
}
package com.tutorialspoint;
import java.util.List;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
public class WebServiceTester {
private Client client;
private String REST_SERVICE_URL = "http://localhost:8080/UserManagement/rest/UserService/users";
private static final String SUCCESS_RESULT="<result>success</result>";
private static final String PASS = "pass";
private static final String FAIL = "fail";
private void init(){
this.client = ClientBuilder.newClient();
}
public static void main(String[] args){
WebServiceTester tester = new WebServiceTester();
//initialize the tester
tester.init();
//test get all users Web Service Method
tester.testGetAllUsers();
//test get user Web Service Method
tester.testGetUser();
//test update user Web Service Method
tester.testUpdateUser();
//test add user Web Service Method
tester.testAddUser();
//test delete user Web Service Method
tester.testDeleteUser();
}
//Test: Get list of all users
//Test: Check if list is not empty
private void testGetAllUsers(){
GenericType<List<User>> list = new GenericType<List<User>>() {};
List<User> users = client
.target(REST_SERVICE_URL)
.request(MediaType.APPLICATION_XML)
.get(list);
String result = PASS;
if(users.isEmpty()){
result = FAIL;
}
System.out.println("Test case name: testGetAllUsers, Result: " + result );
}
//Test: Get User of id 1
//Test: Check if user is same as sample user
private void testGetUser(){
User sampleUser = new User();
sampleUser.setId(1);
User user = client
.target(REST_SERVICE_URL)
.path("/{userid}")
.resolveTemplate("userid", 1)
.request(MediaType.APPLICATION_XML)
.get(User.class);
String result = FAIL;
if(sampleUser != null && sampleUser.getId() == user.getId()){
result = PASS;
}
System.out.println("Test case name: testGetUser, Result: " + result );
}
//Test: Update User of id 1
//Test: Check if result is success XML.
private void testUpdateUser(){
Form form = new Form();
form.param("id", "1");
form.param("name", "suresh");
form.param("profession", "clerk");
String callResult = client
.target(REST_SERVICE_URL)
.request(MediaType.APPLICATION_XML)
.put(Entity.entity(form,
MediaType.APPLICATION_FORM_URLENCODED_TYPE),
String.class);
String result = PASS;
if(!SUCCESS_RESULT.equals(callResult)){
result = FAIL;
}
System.out.println("Test case name: testUpdateUser, Result: " + result );
}
//Test: Add User of id 2
//Test: Check if result is success XML.
private void testAddUser(){
Form form = new Form();
form.param("id", "2");
form.param("name", "naresh");
form.param("profession", "clerk");
String callResult = client
.target(REST_SERVICE_URL)
.request(MediaType.APPLICATION_XML)
.post(Entity.entity(form,
MediaType.APPLICATION_FORM_URLENCODED_TYPE),
String.class);
String result = PASS;
if(!SUCCESS_RESULT.equals(callResult)){
result = FAIL;
}
System.out.println("Test case name: testAddUser, Result: " + result );
}
//Test: Delete User of id 2
//Test: Check if result is success XML.
private void testDeleteUser(){
String callResult = client
.target(REST_SERVICE_URL)
.path("/{userid}")
.resolveTemplate("userid", 2)
.request(MediaType.APPLICATION_XML)
.delete(String.class);
String result = PASS;
if(!SUCCESS_RESULT.equals(callResult)){
result = FAIL;
}
System.out.println("Test case name: testDeleteUser, Result: " + result );
}
}
现在在Eclipse中运行测试器。右键单击该文件,然后按照以下选项 **Run as – > Java Application ** 。您将在Eclipse控制台中看到以下结果−
测试用例名称:testGetAllUsers,结果:通过
测试用例名称:testGetUser,结果:通过
测试用例名称:testUpdateUser,结果:通过
测试用例名称:testAddUser,结果:通过
测试用例名称:testDeleteUser,结果:通过