2

我正在开发使用微配置文件休息客户端的应用程序。并且那个休息客户端应该发送带有各种 http 标头的 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());

通用休息客户端代码:

@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);
}
4

1 回答 1

2

根据规范,您可以使用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做任何你需要的东西。如果这仍然不够,并且您确实需要从服务调用中传递内容,则可以使用自定义@RequestScopebean,例如:

@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);
    }
}
于 2020-10-10T02:58:24.037 回答