带有Spring Boot Controller的带有参数的RestTemplate GET

时间:2019-11-19 10:08:57

标签: rest api spring-boot kotlin resttemplate

我正在创建一个微服务,该服务接收来自Rest Template请求到API的数据。我在localhost:8080运行微服务,在localhost:13001运行API,并用Postman对其进行测试。测试方法返回String。当请求具有参数时会出现问题。使用下面的代码,我总会得到“ 404 Not Found”。但是,当API控制器没有任何参数时-方法有效。无法解决此问题。

序列:

1)邮递员(GET http://localhost:8080/test

2)微服务控制器(Rest模板交换)->下面的代码

@RequestMapping(
        method                          = [RequestMethod.GET],
        produces                        = [MediaType.APPLICATION_JSON_VALUE],
        path                            = ["/test"],
        params                          = ["workspace_id"]
        )
@ResponseBody
fun test(
        authentication                  : OAuth2Authentication,
        @RequestParam(value             = "workspace_id")
        workspaceId                     : UUID
)                                       : String
{
    return serviceDashboard.get(authentication, workspaceId)
}

3)休息模板(获取http://localhost:13001/test?workspace_id=.....。)->下面的代码

    @Autowired
lateinit var restTemplate               : RestTemplate

    override fun get(
        authentication                  : OAuth2Authentication,
        workspaceId                     : UUID
)                                       : String
{
    //Header
    val token                           = (authentication.details as OAuth2AuthenticationDetails).tokenValue
    val headers                         = HttpHeaders()
    headers.setBearerAuth(token)
    val entity                          = HttpEntity<Any>(headers)
    //Parameters
    val params                          = HashMap<String, UUID>()
    params["workspace_id"]              = workspaceId
    //URI
    val endpoint                        = URI.create("http://localhost:13001/test")

    return restTemplate.exchange(endpoint.toString(), HttpMethod.GET, entity, String::class.java, params).body!!
}

4)API控制器(返回数据)->下面的代码

-----------非工作版本----------------

@GetMapping(
        produces                        = [MediaType.APPLICATION_JSON_VALUE],
        params                          = ["workspace_id"],
        path                            = ["/test"])
@ResponseBody
fun test(
        @RequestParam(value = "workspace_id")
        workspaceId                     : UUID
)                                       : String
{
    if ( workspaceId.toString() == "650a539a-0356-467e-a0d0-71d472c41aae") return "It works"
    else return "It doesn't work"
}

-----------工作版本----------------

@GetMapping(
        produces                        = [MediaType.APPLICATION_JSON_VALUE]
        path                            = ["/test"])
@ResponseBody
fun test()                              : String
{
    return "It works"
}

1 个答案:

答案 0 :(得分:0)

您在课程级别使用的注释是什么。 您需要使用@RestController。