webservice 入門筆記四發送header信息

有時候,webservice方法傳遞的信息是放在header中的。比如權限認證信息等。

 

在接口中增加一個方法:

@WebResult(name="user")
   public List<User> list(@WebParam(header=true, name="anthInfo")String authInfo);
 

實現如下:

@Override
   public List<User>list(String authInfo) {
      System.out.println(authInfo);
      if("123456".equals(authInfo)){
         returnusers;
      }else {
         System.out.println("auth error!");
         returnnull;
      }
   }


Test方法如下:

 

 /**
          * <p>Title: 帶header信息</p>
          * <p>Description: </p>
          * @author zhutulang
          * @version 1.0
          * @throws SOAPException
          * @throws IOException
          * @throws JAXBException
          */
         @Test
         public void test4() throws SOAPException, IOException,JAXBException {
      //1.創建服務
      URL url = new URL(wsdlUrl);
      QName qName = new QName(namespaceUrl, "MyServiceInterImplService");
      Service service = Service.create(url, qName);
     
      //2.創建Dispatch
      Dispatch<SOAPMessage> dispatch =
            service.createDispatch(new QName(namespaceUrl, "MyServiceInterImplPort"), SOAPMessage.class, Service.Mode.MESSAGE);
     
      //3.創建SOAPMessage
      SOAPMessage msg = MessageFactory.newInstance().createMessage();
      SOAPEnvelope envelope = msg.getSOAPPart().getEnvelope();
      SOAPBody body = envelope.getBody();
     
      //header信息
      SOAPHeader header = envelope.getHeader();
      if(header == null){
         header = envelope.addHeader();
      }
      QName hname = new QName(namespaceUrl, "authInfo", "ns");
      header.addHeaderElement(hname).setValue("123456");
     
      //4.創建QName來指定消息中傳遞的數據
      QName ename = new QName(namespaceUrl, "list", "ns");
      body.addBodyElement(ename);
      msg.writeTo(System.out);
      System.out.println();
     
      //5.通過Distpatch傳遞信息
      SOAPMessage responseMsg = dispatch.invoke(msg);
      responseMsg.writeTo(System.out);
      System.out.println();
     
      //6.將響應的消息轉換爲dom對象
      Document doc =  responseMsg.getSOAPBody().extractContentAsDocument();
      NodeList nl = doc.getElementsByTagName("user");
      JAXBContext ctx = JAXBContext.newInstance(User.class);
      for(int i=0;i<nl.getLength();i++) {
         Node n = nl.item(i);
         User u = (User)ctx.createUnmarshaller().unmarshal(n);
         System.out.println(u);
      }
   }

 相關的代碼下載:http://download.csdn.net/detail/zhutulang/9487929     

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章