Spring RestTemplate מספק דרך נוחה לבדיקת שירותי האינטרנט RESTful.
Spring RestTemplate
- המחלקה Spring RestTemplate היא חלק מ-
spring-web
, שהוכנסה ב-Spring 3. - ניתן להשתמש ב-RestTemplate כדי לבדוק שירותי אינטרנט RESTful המבוססים על HTTP, היא אינה תומכת בפרוטוקול HTTPS.
- מחלקת RestTemplate מספקת לנו שיטות מוטענות לשונות לשיטות HTTP שונות, כגון GET, POST, PUT, DELETE וכדומה.
דוגמא ל-Spring RestTemplate
נביט כעת בדוגמה של Spring RestTemplate, בה נבדוק שירותי REST שנוצרו במאמר של Spring Data JPA. הטבלה למטה ממחישה את ה-URIs שתומכים בשירות רשת זה. .tg {border-collapse:collapse;border-spacing:0;border-color:#999;} .tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#999;color:#444;background-color:#F7FDFA;} .tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#999;color:#fff;background-color:#26ADE4;} .tg .tg-baqh{text-align:center;vertical-align:top} .tg .tg-yw4l{vertical-align:top}
URI | HTTP Method | Description |
---|---|---|
/springData/person | GET | Get all persons from database |
/springData/person/{id} | GET | Get person by id |
/springData/person | POST | Add person to database |
/springData/person | PUT | Update person |
/springData/person/{id} | DELETE | Delete person by id |
בואו נתחיל ביצירת פרוייקט לקוח REST כדי לבדוק את שירותי הרשת הללו. התמונה למטה מציגה את פרוייקט הדוגמה הסופי שלנו עם Spring RestTemplate.
תלותי Maven של Spring RestTemplate
אנו זקוקים לתלותי spring-core
, spring-context
עבור מסגרת Spring. לאחר מכן, אנו זקוקים לארטיפקט spring-web
המכיל את מחלקת RestTemplate
. אנו גם זקוקים ל־jackson-mapper-asl
עבור תמיכה ב־JSON של Spring דרך API של Jackson.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.journaldev.spring</groupId>
<artifactId>SpringRestTemplate</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<spring.framework>4.3.0.RELEASE</spring.framework>
<spring.web>3.0.2.RELEASE</spring.web>
<serializer.version>2.8.1</serializer.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.framework}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.framework}</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.web}</version>
</dependency>
</dependencies>
</project>
מחלקת תצורה של Spring
עלינו להגדיר בין של Spring עבור מחלקת RestTemplate, וזה נעשה במחלקת AppConfig
.
package com.journaldev.spring.config;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
@Configuration
@ComponentScan("com.journaldev.spring")
public class AppConfig {
@Bean
RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
MappingJacksonHttpMessageConverter converter = new MappingJacksonHttpMessageConverter();
converter.setObjectMapper(new ObjectMapper());
restTemplate.getMessageConverters().add(converter);
return restTemplate;
}
}
שים לב ש־RestTemplate משתמשת ב־MessageConverter ואנו צריכים להגדיר מאפיין זה בבין של RestTemplate. בדוגמה שלנו אנו משתמשים ב־MappingJacksonHttpMessageConverter
כדי לשלוף נתונים מתוך פורמט JSON.
מחלקת מודל
מאחר ואנו מנסים להמיר JSON שחזר על ידי שירות האינטרנט שלנו לאובייקט Java באמצעות Jackson Mapper, עלינו ליצור את מחלקת המודל עבור זה. שימו לב כי מחלקת המודל הזו תהיה דומה מאוד למחלקת המודל המשמשת בשירות האינטרנט, למעט שכאן לא נזקק להערות JPA.
package com.journaldev.spring.model;
public class Person {
private Long id;
private Integer age;
private String firstName;
private String lastName;
public Person() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString() {
return "Person{" + "id=" + id + ", age=" + age + ", firstName='" + firstName + '\'' + ", lastName='" + lastName
+ '\'' + '}';
}
}
מחלקת הלקוח של Spring RestTemplate
השלב הסופי הוא ליצור את מחלקות הלקוח שישתמשו ב- RestTemplate bean המוגדר לעיל.
package com.journaldev.spring.config;
import java.util.List;
import org.springframework.http.HttpStatus;
import com.journaldev.spring.model.Person;
public interface PersonClient {
List<Person> getAllPerson();
Person getById(Long id);
HttpStatus addPerson(Person person);
void updatePerson(Person person);
void deletePerson(Long id);
}
package com.journaldev.spring.config;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.journaldev.spring.model.Person;
@Service
public class PersonClientImpl implements PersonClient {
@Autowired
RestTemplate restTemplate;
final String ROOT_URI = "https://localhost:8080/springData/person";
public List<Person> getAllPerson() {
ResponseEntity<Person[]> response = restTemplate.getForEntity(ROOT_URI, Person[].class);
return Arrays.asList(response.getBody());
}
public Person getById(Long id) {
ResponseEntity<Person> response = restTemplate.getForEntity(ROOT_URI + "/"+id, Person.class);
return response.getBody();
}
public HttpStatus addPerson(Person person) {
ResponseEntity<HttpStatus> response = restTemplate.postForEntity(ROOT_URI, person, HttpStatus.class);
return response.getBody();
}
public void updatePerson(Person person) {
restTemplate.put(ROOT_URI, person);
}
public void deletePerson(Long id) {
restTemplate.delete(ROOT_URI + id);
}
}
הקוד הוא ברור מאליו, אנו קוראים לשיטות RestTemplate על פי ה-URI ושיטת ה-HTTP ועל ידי מעבר אובייקט בקשה מתאים אם נדרש.
מחלקת הבדיקות של Spring RestTemplate
הגיע הזמן לבדוק את פרויקט הדוגמה שלנו של Spring RestTemplate, המחלקה למטה מציגה כיצד להשתמש בשיטות RestTemplate בדרך של Spring.
package com.journaldev.spring;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.http.HttpStatus;
import com.journaldev.spring.config.AppConfig;
import com.journaldev.spring.config.PersonClient;
import com.journaldev.spring.model.Person;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
PersonClient client = applicationContext.getBean(PersonClient.class);
System.out.println("Getting list of all people:");
for (Person p : client.getAllPerson()) {
System.out.println(p);
}
System.out.println("\nGetting person with ID 2");
Person personById = client.getById(2L);
System.out.println(personById);
System.out.println("Adding a Person");
Person p = new Person();
p.setAge(50);
p.setFirstName("David");
p.setLastName("Blain");
HttpStatus status = client.addPerson(p);
System.out.println("Add Person Response = " + status);
applicationContext.close();
}
}
כאשר אני מריץ את התוכנית לעיל נגד הקונפיגורציה המקומית שלי, אני מקבל את הפלט הבא.
Getting list of all people:
Person{id=2, age=30, firstName='Oksi', lastName=' Bahatskaya'}
Person{id=1, age=30, firstName='Vlad', lastName='Mateo'}
Getting person with ID 2
Person{id=2, age=30, firstName='Oksi', lastName=' Bahatskaya'}
Adding a Person
Add Person Response = 201
התמונה למטה מראה את נתוני טבלת מסד הנתונים של השירות האינטרנט לפני ואחרי ביצוע התוכנית לעיל. כפי שניתן לראות, פלט התוכנית תואם לנתוני טבלה דוגמתיים. זהו הכל בדוגמת Spring RestTemplate, ניתן להוריד את הפרויקט מהקישור למטה.
הורד דוגמת פרויקט Spring RestTemplate
הפנייה: מסמך API
Source:
https://www.digitalocean.com/community/tutorials/spring-resttemplate-example