SpringBoot——HTTP接口服务端以及客户端实例

文章目录

  • 一、HTTP接口实例
    • 1、服务端代码
    • 2、客户端代码
    • 3、测试结果
  • 二、SpringBoot中RestTemplate

一、HTTP接口实例

我们经常需要在两个系统之间进行一些数据的交互,这时候我们就需要开发数据交互接口。

一般来说,遇到比较多的接口有HTTP接口、WebService接口、FTP文件传输。今天我要来学习一下在SpringBoot框架下进行简单的HTTP接口的开发。

1、服务端代码

提供接口。接口地址:http://localhost:8080/testApi/get

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 1、提供接口。接口地址:http://localhost:8080/testApi/get
 * @author zll
 * @version 1.0
 * @date 2020/6/10 10:50
 */
@RestController
//@Api(tags = "接口")
@RequestMapping("/testApi")
public class TestApiRest {
     

    @GetMapping("/get")
//    @ApiOperation("获取数据")
    public JSONObject testGet() {
     
        Map map=new HashMap();
        map.put("name","杨幂");
        map.put("age",18);
        map.put("sex","女");

        JSONObject js = new JSONObject();
        js.put("data",map);
        js.put("success", true);
        js.put("message", "获取接口数据成功!");
        return js;
    }

}

启动程序,访问接口url地址。访问成功,结果如图:
在这里插入图片描述

2、客户端代码

在另外一个项目中进行相应客户端代码的开发。设置支持定时任务,设置访问接口方法定时每15秒钟执行一次。有一些注意点:

(1)首先需要启动类加@EnableScheduling注解,支持简单定时任务。
(2)测试类加@Component注解,实现bean的注入。

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zll
 * @version 1.0
 * @date 2020/6/10 12:59
 */
@Component
public class GetApiRest {
     
    @Scheduled(cron = "*/15 * * * * ?")
    public void test() {
     

        String url = "http://localhost:8080/testApi/get";
        RestTemplate template = new RestTemplate();

        Map map=new HashMap();
        String str = template.getForObject(url, String.class);
        System.out.println(str);
    }
}

3、测试结果

(1)启动服务端程序;
(2)启动服务端程序。

运行结果:每十五分钟获取接口数据成功。
在这里插入图片描述

二、SpringBoot中RestTemplate

传统情况下在java代码里访问restful服务,一般使用Apache的HttpClient。不过此种方法使用起来太过繁琐。spring提供了一种简单便捷的模板类来进行操作,这就是RestTemplate。

参考学习链接:RestTemplate

你可能感兴趣的:(SpringBoot,java)