簡體   English   中英

使用 Spring RestTemplate 向每個 REST 請求添加查詢參數

[英]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.HttpRequestWrapperspring-web可用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM