java如何在微文件rest客户端中动态添加HTTP头?
我正在开发应用程序,它使用rest客户端。rest客户端应该发送带有各种http头的rest请求。某些标题名称会动态更改。我的rest客户端应该是通用的,但我没有找到如何实现这种行为。 根据文档,您需要通过注释指定实现中的所有头名称,这不是通用的。有没有办法“破解”它并以编程方式添加HTTP头
提前谢谢
GenericRestClient genericRestClient = null;
Map<String, Object> appConfig = context.appConfigs();
String baseUrl = (String) appConfig.get("restClient.baseUrl");
path = (String) appConfig.get("restClient.path");
try {
genericRestClient = RestClientBuilder.newBuilder()
.baseUri(new URI(baseUrl)).build(GenericRestClient.class);
}catch(URISyntaxException e){
logger.error("",e);
throw e;
}
Response response = genericRestClient.sendMessage(path, value);
logger.info("Status: "+response.getStatus());
logger.info("Response body: "+response.getEntity().toString());
通用rest客户端代码:
@RegisterRestClient
public interface GenericRestClient {
@POST
@Path("{path}")
@Produces("application/json")
@Consumes("application/json")
public Response sendMessage(<here should go any map of custom headers>, @PathParam("path") String pathParam, String jsonBody);
}
# 1 楼答案
根据spec,可以使用
ClientHeadersFactory
。大概是这样的:不能将值直接传递给
ClientHeadersFactory
;但是,如果通过JAX-RS调用您自己的服务,您可以直接访问传入请求的头。您还可以@Inject
任何需要的内容。如果这仍然不够,并且您确实需要从服务调用传递内容,那么您可以使用定制的@RequestScope
bean,例如: