Java rest util:构建rest url的优雅方式

问题描述 投票:0回答:3

目前,我正在使用字符串连接构建URL。

String url = "http://localhost:8080/bo/" + docId;

HttpEntity<String> httpEntity = this.handleJWT();

restTemplate
    .exchange(
        url,
        HttpMethod.DELETE,
        httpEntity,
        Void.class
    );

使用java构建rest url是否更优雅?

java spring spring-boot
3个回答
2
投票

你也可以使用UriComponentsBuiler

String url = "http://localhost:8080/bo/{docId}"
UriComponentsBuilder
            .fromHttpUrl(url)
            .buildAndExpand(docId)
            .toUriString();

并且应该从属性中注入url。


2
投票

你可以这样做:

String url = "http://localhost:8080/bo/{docId}";

restTemplate
.exchange(
    url,
    HttpMethod.DELETE,
    httpEntity,
    Void.class,
    docId
);

0
投票

就在这里。当然不推荐像你这样的硬编码网址。

Spring Boot Rest允许您通过@RequestMapping等注释将请求映射到URL。

在你的情况下,带有@RestController注释类的方法签名可能是这样的:

@RequestMapping(value = "/bo/{docId}", method = RequestMethod.DELETE)
public void request(@PathVariable("docId") int docId){
   ...
}

例如。在浏览器中输入localhost:8080 / bo / 123将导致方法调用,其中“123”是传递的参数。

使用此布局,您可以非常方便地触发方法调用。我建议你通过这个Spring Boot Rest教程。它为如何正确设置具有宁静交互的Spring Boot应用程序提供了一个很好的起点。

© www.soinside.com 2019 - 2024. All rights reserved.