-
新建项目
java版本选择11
-
项目文件如下
-
controller.mockController
//负责处理api接口
@RestController
public class mockController {
@Autowired
private mockService mockService;
@RequestMapping("/message")
public mockData getMockData() throws Exception {
mockData data = new mockData();
data.setMessage(mockService.getMockData());
return data;
}
}
- pojo.mockData
//声明和定义变量
@Getter
@Setter
public class mockData {
private String message;
}
- service.mockService
//service接口类,负责定义、声明变量和函数(方法)
public interface mockService {
String getMockData() throws Exception;
}
- serviceimpl.mockData
//service实现类,负责实现接口定义的函数(方法)
@Service
public class mockData implements mockService {
// Get data from mock api and return
@Override
public String getMockData() throws Exception {
// Create a neat value object to hold the URL
URL url = new URL("https://run.mocky.io"); // 该mock网址不全,请自行找合适的mock数据
// Open a connection(?) on the URL(??) and cast the response(???)
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Now it's "open", we can set the request method, headers etc.
connection.setRequestProperty("accept", "application/json");
// This line makes the request
InputStream responseStream = connection.getInputStream();
// Manually converting the response body InputStream to Object using Jackson
ObjectMapper mapper = new ObjectMapper();
Object response = mapper.readValue(responseStream, Object.class);
// Finally we have the response
System.out.println(response);
LinkedHashMap map = (LinkedHashMap) response;
String message = (String) map.get("message");
return message;
}
}
- application.properties
//配置参数
server.port=81
// user.name = 'admin'
// user.password = 'psw'
// 在其他类中可通过 @Value("${user.name}") / @Value("${user.password}")
// 取出application.properties文件下存储的值
- 请求数据