简体   繁体   English

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

[英]Add Query Parameter to Every REST Request using Spring RestTemplate

Is there a way to add a query parameter to every HTTP request performed by RestTemplate in Spring?有没有办法为 Spring 中RestTemplate执行的每个 HTTP 请求添加查询参数?

The Atlassian API uses the query parameter os_authType to dictate the authentication method so I'd like to append ?os_authtype=basic to every request without specifying it all over my code. Atlassian API 使用查询参数os_authType来指定身份验证方法,因此我想将?os_authtype=basic附加到每个请求,而不是在我的代码中全部指定它。

Code代码

@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;    
    }
}

You can write custom RequestInterceptor that implements ClientHttpRequestInterceptor您可以编写实现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);
    }
}

Now we need to configure our RestTemplate to use it现在我们需要配置我们的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;
    }
}

For the ones interested in logic to add a query parameter, as HttpRequest is immutable a wrapper class is needed.对于那些对添加查询参数的逻辑感兴趣的人,由于 HttpRequest 是不可变的,因此需要一个包装类。

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

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

}

Then in your ClientHttpRequestInterceptor you can do something like然后在您的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);
    }

Update Since spring 3.1 wrapper class org.springframework.http.client.support.HttpRequestWrapper is available in spring-web更新自 spring 3.1 包装类org.springframework.http.client.support.HttpRequestWrapperspring-web可用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM