用工具加WebSevice链接生成的Client

  1. MaterialRequisitionControllerService service=new MaterialRequisitionControllerService();
  2. MaterialRequisition materialRequisitionPort = service.getMaterialRequisitionPort();
  3. //添加HTTP消息头
  4. Map<String, List<String>> requestHeaders = new HashMap<>();
  5. requestHeaders.put("Company-Id", Collections.singletonList("902"));
  6. BindingProvider bindingProvider = (BindingProvider)materialRequisitionPort;
  7. bindingProvider.getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, requestHeaders);

动态调用方式

方法1:RequestContext添加HTTP标头

  1. JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
  2. Client client = dcf.createClient("http://localhost/webservice/material?wsdl");
  3. @SuppressWarnings("unchecked")
  4. Map<String, List<String>> headers =
  5. (Map<String, List<String>>)client.getRequestContext().get(Message.PROTOCOL_HEADERS);
  6. if (headers == null) {
  7. headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
  8. client.getRequestContext().put(Message.PROTOCOL_HEADERS, headers);
  9. }
  10. headers.put("Company-Id", Collections.singletonList("902"));
  11. Object[] ojs = client.invoke("updateStatus", "233483333", 2);

方法2:自定义拦截器添加HTTP标头

自定义拦截器:

  1. import org.apache.cxf.interceptor.Fault;
  2. import org.apache.cxf.message.Message;
  3. import org.apache.cxf.phase.AbstractPhaseInterceptor;
  4. import org.apache.cxf.phase.Phase;
  5. import java.util.*;
  6. public class CompanyInterceptor extends AbstractPhaseInterceptor<Message> {
  7. private static final String COMPANY_ID = "902";
  8. public CompanyInterceptor() {
  9. //准备请求时进行拦截
  10. super(Phase.PREPARE_SEND);
  11. }
  12. @Override
  13. public void handleMessage(Message message) throws Fault {
  14. Map<String, List<String>> headers = new HashMap<>(1);
  15. headers.put("Company-Id", Collections.singletonList(COMPANY_ID));
  16. message.put(Message.PROTOCOL_HEADERS, headers);
  17. }
  18. }

调用:

  1. JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
  2. Client client = dcf.createClient("http://localhost/webservice/material?wsdl");
  3. client.getOutInterceptors().add(new CompanyInterceptor());
  4. Object[] ojs = client.invoke("updateStatus", "233483333", 2);