how add Message context headers to apache axis 2 Java

此生再无相见时 提交于 2019-12-10 20:44:51

问题


I am working on web services. I want to know how do we add headers to SOAP request in JAX-WS type web services.

Consider My header like this.

    Map<String, List<String>> headers = new HashMap<String, List<String>>();
    headers.put("Username", Collections.singletonList("aaaa"));
    headers.put("Password", Collections.singletonList("aaaa"));

I have stub object in my client class. I am using Apache Axis 2. All the classes are automatically generated.

SimpleSTub stub = new Simplestub();

I want to add this header information in client.

MessageContext.HTTP_REQUEST_HEADERS, headers

Edit

The actual implementation in a normal class found as

private static final String WS_URL = "http://localhost:9999/ws/hello?wsdl";

public static void main(String[] args) throws Exception {

URL url = new URL(WS_URL); QName qname = new QName("http://ws.mkyong.com/", "HelloWorldImplService");

Service service = Service.create(url, qname);
HelloWorld hello = service.getPort(HelloWorld.class);

/*******************UserName & Password ******************************/
Map<String, Object> req_ctx = ((BindingProvider)hello).getRequestContext();
req_ctx.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, WS_URL);

Map<String, List<String>> headers = new HashMap<String, List<String>>();
headers.put("Username", Collections.singletonList("mkyong"));
headers.put("Password", Collections.singletonList("password"));
req_ctx.put(MessageContext.HTTP_REQUEST_HEADERS, headers);
/**********************************************************************/

System.out.println(hello.getHelloWorldAsString());

Can any one tell how to achieve this.

Thanks.


回答1:


You're sort of on your way to the solution with what you already have. The most basic way to achieve this is

  1. Within your client code, obtain a reference to the MessageContext through the BindingProvider on your SimpleStub

    Map<String,Object> context = ((BindingProvder)stub).getRequestContext()
    Map<String,List> headers = context.get(MessageContext.HTTP_REQUEST_HEADERS)
    
  2. Update the map and stuff it back in the request context object

    context.put(MessageContext.HTTP_REQUEST_HEADERS,headers)
    

    The above is all well and good. If however you're trying to do what I presume is add authentication parameters, the recommended way is

    context.put(BindingProvder.USERNAME_PROPERTY,"username");
    context.put(BindingProvder.PASSWORD_PROPERTY,"password");   
    


来源:https://stackoverflow.com/questions/14233714/how-add-message-context-headers-to-apache-axis-2-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!