使用 Spring RestTemplate 向每个 REST 请求添加查询参数 [英] Add Query Parameter to Every REST Request using Spring RestTemplate
本文介绍了使用 Spring RestTemplate 向每个 REST 请求添加查询参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法在 Spring 中为 RestTemplate
执行的每个 HTTP 请求添加一个查询参数?
Is there a way to add a query parameter to every HTTP request performed by RestTemplate
in Spring?
Atlassian API 使用查询参数 os_authType
来指定身份验证方法,因此我想将 ?os_authtype=basic
附加到每个请求中,而无需在我的整个请求中指定它代码.
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.
代码
@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;
}
}
推荐答案
您可以编写实现 ClientHttpRequestInterceptor
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
来使用它
Now we need to configure our RestTemplate
to use it
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;
}
}
这篇关于使用 Spring RestTemplate 向每个 REST 请求添加查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文