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

  1. 新建项目
    java版本选择11在这里插入图片描述
    在这里插入图片描述

  2. 项目文件如下
    在这里插入图片描述

  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. 请求数据
    在这里插入图片描述
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值