gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 04:20:41 25 4
gpt4 key购买 nike

有没有办法在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com