我正在开发使用微型配置文件其余客户端的应用程序。其余客户端应发送带有各种http标头的REST请求。一些标题名称会动态更改。我的小档案其余客户应该是通用的,但是我没有找到如何实现这种行为的方法。 根据文档,您需要通过注释指定实现中的所有标头名称,但这不是通用的。有什么方法可以“ hack”它并以编程方式添加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());
通用的休息客户代码:
@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);
}
答案 0 :(得分:0)
根据spec,您可以使用ClientHeadersFactory
。像这样:
public class CustomClientHeadersFactory implements ClientHeadersFactory {
@Override public MultivaluedMap<String, String> update(
MultivaluedMap<String, String> incomingHeaders,
MultivaluedMap<String, String> clientOutgoingHeaders
) {
MultivaluedMap<String, String> returnVal = new MultivaluedHashMap<>();
returnVal.putAll(clientOutgoingHeaders);
returnVal.putSingle("MyHeader", "generated");
return returnVal;
}
}
@RegisterRestClient
@RegisterClientHeaders(CustomClientHeadersFactory.class)
public interface GenericRestClient {
...
}
您不能将值直接传递给ClientHeadersFactory
;但是,如果您自己的服务是通过JAX-RS调用的,则可以直接访问传入请求的标头。您也可以@Inject
进行任何操作。如果这还不够,并且您确实需要通过服务调用传递信息,则可以使用自定义的@RequestScope
bean,例如:
@RequestScope
class CustomHeader {
private String name;
private String value;
// getters/setters
}
public class CustomClientHeadersFactory implements ClientHeadersFactory {
@Inject CustomHeader customHeader;
@Override public MultivaluedMap<String, String> update(
MultivaluedMap<String, String> incomingHeaders,
MultivaluedMap<String, String> clientOutgoingHeaders
) {
MultivaluedMap<String, String> returnVal = new MultivaluedHashMap<>();
returnVal.putAll(clientOutgoingHeaders);
returnVal.putSingle(customHeader.getName(), customHeader.getValue());
return returnVal;
}
}
class Client {
@Inject CustomHeader customHeader;
void call() {
customHeader.setName("MyHeader");
customHeader.setValue("generated");
...
Response response = genericRestClient.sendMessage(path, value);
}
}