有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何自动设置随每个请求而变化的JAXWS HTTP头

我想在每个SOAPJAX-WS请求上设置一个动态生成的HTTP头

如果我想在每个JAX-WS请求上设置相同的HTTP头,我可以使用技术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头。本质上,我希望包含一个X-RequestId头或类似的随机值,以便接收服务器能够区分在超时时由Java客户端或(更糟糕的)内联HTTP代理复制的请求

此外,如果JAX-WS重试相同的调用,我不希望它重新生成头(显然)

请注意,我的应用程序已经包含在port.echoString(对web服务的大量调用)的等价部分中。我无法手动更改每次此类呼叫前的标题,因为:

  • 它们共享同一个绑定提供程序,这不是线程安全的(即,用户A可以更改头,用户B可以更改头,然后用户A可以调用,然后用户B可以调用,然后传递相同的头)
  • 这需要对整个代码进行修改

我想做的是在序列化每个请求的类中添加一些东西,以便在序列化时添加头

相关但不重复的问题:


共 (1) 个答案

  1. # 1 楼答案

    至于惟一值方面,您可以使用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头。但是,在您的例子中,您希望将X-RequestId设置为上面讨论的UUID