实体类
@Data
public class User {
private Integer id;
private String username;
public User() {}
public User(Integer id, String username) {
this.id = id;
this.username = username;
}
}
Controller
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
@GetMapping
public List<User> getUser() {
List<User> list = new ArrayList<>();
list.add(new User(1, "张三"));
list.add(new User(2, "李四"));
return list;
}
@GetMapping("/{id}")
public User getUserById(@PathVariable Integer id) {
return new User(id, "法外狂徒张三");
}
@PostMapping
public void add(@RequestBody User user) {
log.info("将要新增的User: {}", user.toString());
}
@PutMapping("/{id}")
public void update(@RequestBody User user, @PathVariable Integer id) {
log.info("传入的用户信息:{}", user.toString());
}
@DeleteMapping("/{id}")
public void delete(@PathVariable Integer id) {
log.info("将要删除ID为{}的user", id);
}
}
引入jar包
<dependency>
<groupId>com.github.lianjiatech</groupId>
<artifactId>retrofit-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
请求体
import java.util.List;
import com.github.lianjiatech.retrofit.spring.boot.annotation.RetrofitClient;
import com.tang.entity.User;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Path;
@RetrofitClient(baseUrl = "${api.user}")
public interface UserApi {
@GET("user")
List<User> getUser();
@GET("user/{id}")
User getUserById(@Path("id")Integer id);
@POST("user")
Void addUser(@Body User user);
@PUT("user/{id}")
Void updateUser(@Body User user,@Path("id") Integer id);
@DELETE("user/{id}")
Void deleteUserById(@Path("id") Integer id);
}
测试类
@Slf4j
@SpringBootTest
@ExtendWith(SpringExtension.class)
class UserApiTest {
@Autowired
private UserApi userApi;
@Test
void testGetUser() {
List<User> user = userApi.getUser();
log.info("得到的用户信息: {}", user);
}
@Test
void testGetUserById() {
User user = userApi.getUserById(1);
log.info("得到的用户信息: {}", user);
}
@Test
void testAddUser() {
userApi.addUser(new User(null, "没有名字"));
}
@Test
void testUpdateUser() {
userApi.updateUser(new User(1, "柴米油盐酱醋茶"), 1);
}
@Test
void testDeleteUser() {
userApi.deleteUserById(1);
}
}
执行
2020-12-10 23:32:35.288 INFO 16664 --- [nio-8080-exec-5] com.tang.controller.UserController : 将要新增的User: User(id=null, username=尼古拉斯)
2020-12-10 23:34:41.452 INFO 16664 --- [nio-8080-exec-8] com.tang.controller.UserController : 将要新增的User: User(id=null, username=尼古拉斯)
2020-12-10 23:38:42.905 INFO 16664 --- [nio-8080-exec-3] com.tang.controller.UserController : 传入的用户信息:User(id=1, username=柴米油盐酱醋茶)
2020-12-10 23:40:31.354 INFO 16664 --- [nio-8080-exec-5] com.tang.controller.UserController : 将要删除ID为1的user