使用 Spring RestTemplate 将查询参数添加到每个 REST 请求

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

有没有办法在Spring中为

RestTemplate
执行的每个HTTP请求添加查询参数?

Atlassian API 使用查询参数

os_authType
来指定身份验证方法,因此我想将
?os_authtype=basic
附加到每个请求,而不是在我的代码中指定它。

代码

@Service
public class MyService {

    private RestTemplate restTemplate;

    @Autowired
    public MyService(RestTemplateBuilder restTemplateBuilder, 
            @Value("${api.username}") final String username, @Value("${api.password}") final String password, @Value("${api.url}") final String url ) {
        restTemplate = restTemplateBuilder
                .basicAuthorization(username, password)
                .rootUri(url)
                .build();    
    }

    public ResponseEntity<String> getApplicationData() {            
        ResponseEntity<String> response
          = restTemplate.getForEntity("/demo?os_authType=basic", String.class);

        return response;    
    }
}
java spring rest spring-boot resttemplate
3个回答
5
投票

对于那些对添加查询参数的逻辑感兴趣的人,由于 HttpRequest 是不可变的,所以需要一个包装类。

class RequestWrapper {
    private final HttpRequest original;
    private final URI newUriWithParam;

    ...
    public HttpMethod getMethod() { return this.original.method }
    public URI getURI() { return newUriWithParam }

}

然后在你的

ClientHttpRequestInterceptor
中你可以做类似

的事情
public ClientHttpResponse intercept(
        request: HttpRequest,
        body: ByteArray,
        execution: ClientHttpRequestExecution
    ) {
        URI uri = UriComponentsBuilder.fromUri(request.uri).queryParam("new-param", "param value").build().toUri();
        return execution.execute(RequestWrapper(request, uri), body);
    }

更新 自 spring 3.1 包装类

org.springframework.http.client.support.HttpRequestWrapper
开始,在
spring-web

中可用

4
投票

您可以编写实现

ClientHttpRequestInterceptor

的自定义 RequestInterceptor
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

public class AtlassianAuthInterceptor implements ClientHttpRequestInterceptor {

    @Override
    public ClientHttpResponse intercept(
            HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
            throws IOException {

        // logic to check if request has query parameter else add it
        return execution.execute(request, body);
    }
}

现在我们需要配置我们的

RestTemplate
来使用它

import java.util.Collections;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;


@Configuration
public class MyAppConfig {

    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory());
        restTemplate.setInterceptors(Collections.singletonList(new AtlassianAuthInterceptor()));
        return restTemplate;
    }
}

0
投票

使用 Spring Boot 3.2.x

@Service
public class MyService {

    private final RestTemplate restTemplate;

    public MyService(
            RestTemplateBuilder restTemplateBuilder,
            @Value("${api.username}") final String username,
            @Value("${api.password}") final String password,
            @Value("${api.url}") final String url) {

        // inject "os_authType" query parameter in every request
        ClientHttpRequestInterceptor interceptor = (request, body, execution) -> {

            HttpRequest modifiedRequest = new HttpRequestWrapper(request) {

                @Override
                public URI getURI() {
                    return ForwardedHeaderUtils.adaptFromForwardedHeaders(request.getURI(), request.getHeaders())
                            .queryParam("os_authType", "basic")
                            .build(true)
                            .toUri();
                }
            };

            return execution.execute(modifiedRequest, body);
        };

        // consider using the new RestClient instead RestTemplate in Srping Boot 3.2.x
        restTemplate = restTemplateBuilder
                .interceptors(interceptor)
                .basicAuthentication(username, password)
                .rootUri(url)
                .build();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.