// 登录获取token (公开接口)
fetch('https://api.demo-springboot.com/v1/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: 'demouser', password: 'demo2024' })
})
.then(res => res.json())
.then(data => {
const token = data.accessToken;
// 获取用户资料 (携带token)
return fetch('https://api.demo-springboot.com/v1/user/profile', {
headers: { 'Authorization': `Bearer ${token}` }
});
})
.then(res => res.json())
.then(profile => console.log('用户资料:', profile));
Spring Boot 项目直接使用 RestTemplate 或 WebClient。无需额外配置。
以下代码使用RestTemplate,携带token获取商品列表(左右滑动)
@Service
public class ProductService {
private final RestTemplate rest = new RestTemplate();
private final String BASE = "https://api.demo-springboot.com/v1";
public List<Product> fetchProducts(String token, int page) {
String url = BASE + "/product/list?page=" + page + "&size=10";
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(token);
HttpEntity<?> entity = new HttpEntity<>(headers);
ResponseEntity<ProductResponse> resp = rest.exchange(
url, HttpMethod.GET, entity, ProductResponse.class);
return resp.getBody().getProducts();
}
}
定义与后端匹配的POJO,使用Lombok简化。
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class Product {
private Long id;
private String name;
private BigDecimal price;
private String category;
}
// 包装分页响应
@Data
public class ProductResponse {
private List<Product> products;
private int totalPages;
}
Android (Java/Kotlin) 可用 Retrofit 或 OkHttp 同样方式请求。iOS 可用 URLSession。流程一致:请求→解析→渲染。