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

标签 java spring rest spring-boot 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;
    }
}

关于java - 使用 Spring RestTemplate 向每个 REST 请求添加查询参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49394414/

相关文章:

c# - 如何在 RestSharp 中发送 POST 请求?

mysql - 两个数据库存储库中的 Spring Data JPA

java - Spring boot schema.sql 不适用于 mysqldump 文件

.net - 在搜索表单中发布或获取?

java - 单元测试-Mockito和Butterknife-如何 mock

java - Spring 3.2 测试,com.jajway 不包含在依赖项中

php - 是否可以在不使用任何库的情况下在 PHP 中使用 POST 请求创建 Restful Web 服务?

java - 具有相同哈希码的两个不相等的对象

java - 当批量大时,JDBC 应用程序挂起进行批量插入

java - 要编写用于分析 Java 源代码的 Eclipse 插件,我必须知道哪一部分?