新建一个Springboot项目,并实现获取数据和输出一个api接口

  1. 新建项目
    java版本选择11新建一个Springboot项目,并实现获取数据和输出一个api接口_第1张图片
    新建一个Springboot项目,并实现获取数据和输出一个api接口_第2张图片

  2. 项目文件如下
    新建一个Springboot项目,并实现获取数据和输出一个api接口_第3张图片

  3. 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;
    }
}
  1. pojo.mockData
//声明和定义变量
@Getter
@Setter
public class mockData {
    private String message;
}
  1. service.mockService
//service接口类,负责定义、声明变量和函数(方法)
public interface mockService {
    String getMockData() throws Exception;
}

  1. 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;
    }
}
  1. application.properties
//配置参数
server.port=81

// user.name = 'admin'
// user.password = 'psw'
// 在其他类中可通过 @Value("${user.name}") / @Value("${user.password}")
// 取出application.properties文件下存储的值
  1. 请求数据
    新建一个Springboot项目,并实现获取数据和输出一个api接口_第4张图片

你可能感兴趣的:(后端,spring,boot)