如何在Spring-ws端点访问HTTP头?

如何在Spring-ws端点中访问HTTP头?

我的代码如下所示:

public class MyEndpoint extends AbstractMarshallingPayloadEndpoint { protected Object invokeInternal(Object arg) throws Exception { MyReq request = (MyReq) arg; // need to access some HTTP headers here return createMyResp(); } } 

invokeInternal()仅获取未编组的JAXB对象作为参数。 如何在invokeInternal()访问请求附带的HTTP头?

一种可能有效的方法是创建一个Servletfilter,将头值存储到ThreadLocal变量,然后在invokeInternal()访问,但是有更好的,更类似Spring的方法吗?

您可以添加这些方法。 TransportContextHolder将在线程局部变量中保存与传输(本例中为HTTP)相关的一些数据。 您可以从TransportContext访问HttpServletRequest

 protected HttpServletRequest getHttpServletRequest() { TransportContext ctx = TransportContextHolder.getTransportContext(); return ( null != ctx ) ? ((HttpServletConnection ) ctx.getConnection()).getHttpServletRequest() : null; } protected String getHttpHeaderValue( final String headerName ) { HttpServletRequest httpServletRequest = getHttpServletRequest(); return ( null != httpServletRequest ) ? httpServletRequest.getHeader( headerName ) : null; } 

我有同样的问题(见另一个问题 )。 我需要在我的WS中添加一个Content-Type标头。 我走了Servletfilter的道路。 大多数情况下,您不需要在Web服务中更改HTTP标头。 但是……理论和实践之间有一段时间存在差异。

您可以通过注入HttpServletRequest来访问Spring SOAP Endpoint中的HTTP头。

例如,您需要获取Autorization标头(使用基本身份validation)。

SOAP请求:

 POST http://localhost:8025/ws HTTP/1.1 Accept-Encoding: gzip,deflate Content-Type: text/xml;charset=UTF-8 SOAPAction: "" Authorization: Basic YWRtaW46YWRtaW4= Content-Length: 287 Host: localhost:8025 Connection: Keep-Alive User-Agent: Apache-HttpClient/4.1.1 (java 1.5)        

@Endpoint java类

 @Endpoint @Slf4j public class TokenEndpoint { public static final String NAMESPACE_URI = "http://abcdef.com/integration/adapter/services/Token"; private static final String AUTH_HEADER = "Authorization"; private final HttpServletRequest servletRequest; private final TokenService tokenService; public TokenEndpoint(HttpServletRequest servletRequest, TokenService tokenService) { this.servletRequest = servletRequest; this.tokenService = tokenService; } @PayloadRoot(namespace = NAMESPACE_URI, localPart = "GetTokenRequest") @ResponsePayload public GetTokenResponse getToken(@RequestPayload GetTokenRequest request) { String auth = servletRequest.getHeader(AUTH_HEADER); log.debug("Authorization header is {}", auth); return tokenService.getToken(request); } }