我想在每个 SOAP JAX-WS 请求上设置动态生成的 HTTP header 。
如果我想在每个 JAX-WS 请求上设置相同 HTTP header ,我可以使用该技术 here ,即
public class MyApplicationClass {
// Inject an instance of the service's port-type.
@WebServiceRef(EchoService.class)
private EchoPortType port;
// This method will invoke the web service operation and send transport headers on the request.
public void invokeService() {
// Set up the Map that will contain the request headers.
Map<String, Object> requestHeaders = new HashMap<String, Object>();
requestHeaders.put(“MyHeader1”, “This is a string value”);
requestHeaders.put(“MyHeader2”, new Integer(33));
requestHeaders.put(“MyHeader3”, new Boolean(true));
// Set the Map as a property on the RequestContext.
BindingProvider bp = (BindingProvider) port;
bp.getRequestContext().put(com.ibm.websphere.webservices.Constants.REQUEST_TRANSPORT_PROPERTIES, requestHeaders);
// Invoke the web services operation.
String result = port.echoString(“Hello, world!”);
}
}
但是,在这里我想为每个请求使用不同的 HTTP header 。本质上,我想包含一个 X-RequestId header 或类似的随机值,以便接收服务器可以区分 Java 客户端或(更糟糕的是)内联 HTTP 代理在超时时重复的请求。
此外,它 JAX-WS 重试相同的调用,我不希望它重新生成 header (显然)。
请注意,我的应用程序已包含在 port.echoString
的等效项中(对 Web 服务的大量调用)。我无法手动更改每个此类调用前面的 header ,因为:
- 它们共享相同的绑定(bind)提供程序,这不是线程安全的(即用户 A 可以更改 header ,用户 B 可以更改 header ,然后用户 A 可以调用,然后用户 B 可以调用,并且相同的 header 已通过)
- 这需要修改整个代码。
我想要做的是向序列化每个请求的类添加一些内容,以在序列化时添加 header 。
相关但不重复的问题:
- java web service client, adding http headers - 不使用 JAX-WS 绑定(bind),即每次调用都必须手动进行
- How to add header to SOAP request? - SOAP header 而非 HTTP header
最佳答案
关于唯一值方面,可以使用JDK的UUID class创建 GUID :
requestHeaders.put("X-RequestId", java.util.UUID.randomUUID().toString());
至于澄清的线程安全问题,基于JAX-WS specification (JSR-224)第 9.3 节 我建议使用 JAX-WS 客户端处理程序来执行此操作,因为处理程序规范标识了线程安全机制:MessageContext :
9.3.3 Handler Implementation Considerations
Handler instances may be pooled by a JAX-WS runtime system. All instances of a specific handler are considered equivalent by a JAX-WS runtime system and any instance may be chosen to handle a particular message. Different handler instances may be used to handle each message of an MEP. Different threads may be used for each handler in a handler chain, for each message in an MEP or any combination of the two. Handlers should not rely on thread local state to share information. Handlers should instead use the message context, see section 9.4.
您可以编写一个中央处理程序类并将其附加到 BindingProvider
的处理程序链,以避免更改您在应用程序中调用服务操作的所有位置。您可以通过编程方式或通过 @HandlerChain 将处理程序添加到处理程序链。 @WebServiceRef
This post描述了如何使用处理程序框架的 MessageContext
来设置您想要的出站 http header 。但是,在您的情况下,您希望使用上面讨论的 UUID
值设置 X-RequestId
。
关于java - 如何自动设置随每个请求而变化的 JAX-WS HTTP header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31565728/