本文主要講述,使用java語言調用webservice的幾種方法,和針對於獲取的報文文件解析的一些看法。
再次之前先推薦一種工具,soapui這個工具可以很好的實現測試webservice的連通性,並且可以直接獲取、
webservice服務上對應的值。
第一部分:調用方法
第一種方式采用soap的方式:下面是需要引用的包axis.jar
import javax.xml.*;
下面附上一部分的測試代碼:
public String getwebservice() throws Exception {
String temp = "";//用來存放返回的報文內容
try {
//實例化一個soap連接對象工廠
SOAPConnectionFactory soapConnFactory = SOAPConnectionFactory.newInstance();
//實例化一個連接對象
SOAPConnection connection = soapConnFactory.createConnection();
//實例化一個消息對象
MessageFactory messageFactory = MessageFactory.newInstance();
//實例化一個消息
SOAPMessage message = messageFactory.createMessage();
//獲取消息中soap消息部分的句柄
SOAPPart soapPart = message.getSOAPPart();
//獲取soap消息部分中的信封句柄
SOAPEnvelope envelope = soapPart.getEnvelope();
//獲取信封中需要填寫的請求報文部分的句柄
SOAPBody body = envelope.getBody();
//以上內容均是實例化各個對象
//下面函數作用為構建請求頭,一共三個參數,其中第一個參數為要訪問webservice中的那個函數的函數名(注意大小寫敏感)
第二個參數需要按照情況來拼接,可以先訪問對方的webservice地址查看是否標簽中有這個元素
第三個參數為訪問空間,也就是對應於wsdl文檔中的namespace內容。
SOAPElement bodyElement = body.addChildElement(envelope.createName(operationName , "web", targetNamespace));
//此訪問距離假定我要訪問的webservice函數有兩個參數
//下面是第一個參數為參數名(大小寫敏感)而第二個參數和第三個參數要視具體的webservice而定
SOAPElement firstElemnt = bodyElement.addChildElement(envelope.createName("" , "", ""));
Name firstName = envelope.createName("type");
//firstName為入參一的值,后面的是入參的類型
firstElemnt.addAttribute(firstName, "String");
firstElemnt.addTextNode();
//以上就是第一個參數的添加
//下面是第二個參數的添加和第一個沒有任何區別
SOAPElement secondElemnt = bodyElement.addChildElement(envelope.createName("" , "", ""));
Name secondName = envelope.createName("type");
secondElemnt.addAttribute(secondName, "String");
secondElemnt.addTextNode();
//下面這句話的意思是保存消息的修改
message.saveChanges();
//下面的webServiceURL為webservice的訪問地址
String destination = webServiceURL;
//下面為調用
SOAPMessage reply = connection.call(message, destination);
//如果返回的消息不為空需要進行處理
if(reply!=null)
{
//這部分的處理就是將返回的值轉換為字符串的格式,也就是流和串之間的轉換
Source source = reply.getSOAPPart().getContent();
Transformer transformer = TransformerFactory.newInstance().newTransformer();
ByteArrayOutputStream myOutStr = new ByteArrayOutputStream();
StreamResult res = new StreamResult();
res.setOutputStream(myOutStr);
transformer.transform(source,res);
//針對於漢子的編碼格式,需要自己制定
temp = myOutStr.toString("UTF-8");
}
//注意!一定要關閉連接
connection.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
if(temp == null)
{
temp = "";
}
return temp;
}
以上就是第一種使用java調用webservice的方法。
有興趣的朋友可以嘗試一下。
好了第一部分暫時到這里,下一篇將會介紹另外一種的調用方式。
