![](/img/trans.png)
[英]Is there a way to add query parameter to every request with Retrofit 2?
[英]Add Query Parameter to Every REST Request using Spring RestTemplate
有沒有辦法為 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;
}
}
您可以編寫實現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;
}
}
對於那些對添加查詢參數的邏輯感興趣的人,由於 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
可用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.