java對(duì)接webservice接口的4種方式總結(jié)
這兩天一直在做外系統(tǒng)對(duì)接,對(duì)方的接口是webservice的形式,調(diào)用起來有些蛋疼,于是在這里記錄一下我嘗試過的調(diào)用WebService的三種方式。
方式一:以HttpURLConnection的方式調(diào)用
String url ="http://127.0.0.1/cwbase/Service/hndg/Hello.asmx?wsdl";
URL realURL = new URL(url);
HttpURLConnection connection = (HttpURLConnection) realURL.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
connection.setRequestProperty("content-length",String.valueOf(xmlData.length));
connection.setRequestMethod("POST");
DataOutputStream printOut = new DataOutputStream(connection.getOutputStream());
printOut.write(xmlOutString.getBytes("UTF-8"));//xmlOutString是自己拼接的xml,這種方式就是通過xml請(qǐng)求接口
printOut.flush();
printOut.close();
// 從連接的輸入流中取得回執(zhí)信息
InputStream inputStream = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(inputStream,"UTF-8");
BufferedReader bufreader = new BufferedReader(isr);
String xmlString = "";
int c;
while ((c = bufreader.read()) != -1) {
xmlString += (char) c; }
isr.close();
//處理返回的xml信息
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document d = db.parse(new ByteArrayInputStream(xmlString.getBytes("UTF-8")));
//從對(duì)方的節(jié)點(diǎn)中取的返回值(節(jié)點(diǎn)名由對(duì)方接口指定)
String returnState = d.getElementsByTagName("ReturnStatus").item(0).getFirstChild().getNodeValue();
方式二:使用apache-cxf生成java類調(diào)用
下載apache-cxf并配置環(huán)境變量(參照J(rèn)AVA環(huán)境變量配置),配置成功后cmd輸入wsdl2java -help即可驗(yàn)證是否成功。
接著在cmd中輸入wsdl2java -encoding utf-8 -d 生成路徑 接口地址,即可在指定路徑生成接口JAVA文件,生成后的JAVA類如下圖:

生成以后調(diào)用起來就很簡(jiǎn)單了,例子如下:
String result = ""; NC65To63ProjectService service = new NC65To63ProjectService(); NC65To63ProjectServicePortType servicePort =service. getNC65To63ProjectServiceSOAP11PortHttp(); result = servicePort.receiptProject(json);
方式三:使用AXIS調(diào)用WebService
為了避免找不到對(duì)方包,所以我直接把包貼在頂上了。
import org.apache.axis.client.Service;
import org.apache.axis.client.Call;
import org.apache.axis.encoding.XMLType;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
String result = "";
String url = "http://127.0.0.1/uapws/service/nc65to63projectsysplugin";//這是接口地址,注意去掉.wsdl,否則會(huì)報(bào)錯(cuò)
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress(url);
String parametersName = "string";//設(shè)置參數(shù)名
call.setOperationName("receiptProject");//設(shè)置方法名
call.addParameter(parametersName, XMLType.XSD_STRING, ParameterMode.IN);//方法參數(shù),1參數(shù)名、2參數(shù)類型、3.入?yún)?
call.setReturnType(XMLType.XSD_STRING);//返回類型
String str = json;
Object resultObject = call.invoke(new Object[] { str });//調(diào)用接口
result = (String) resultObject;
方式四:試用httpclient
public static void main(String args[]) {
// 第一種方法 ----------------------------------------------
JaxWsDynamicClientFactory factory = JaxWsDynamicClientFactory.newInstance();
// 創(chuàng)建客戶端連接
Client client = factory.createClient("http://127.0.0.1:8080/xx/service/userOrg?wsdl");
Object[] res = null;
try {
QName operationName = new QName("http://impl.webservice.userorg.com/","findUser");//如果有命名空間需要加上這個(gè),第一個(gè)參數(shù)為命名空間名稱,調(diào)用的方法名稱
res = client.invoke(operationName, "admin");//后面為WebService請(qǐng)求參數(shù)數(shù)組
System.out.println(res[0]);
}catch (Exception e) {
e.printStackTrace();
}
// 第二種方法 ----------------------------------------------
// 被<![CDATA[]]>這個(gè)標(biāo)記所包含的內(nèi)容將表示為純文本
String xmlData = "<![CDATA[<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<accounts>" +
"<account>" +
"<accId>帳號(hào)ID(必填)</accId>" +
"<userPasswordMD5>密碼</userPasswordMD5>" +
"<userPasswordSHA1>密碼</userPasswordSHA1>" +
"其中userPasswordSHA1標(biāo)簽代表SHA1加密后的密碼,userPasswordMD5標(biāo)簽代表MD5加密后的密碼" +
"<name>姓名</name>" +
"<sn>姓</sn>" +
"<description>描述 </description>" +
"<email>郵箱 </email>" +
"<gender>性別</gender>" +
"<telephoneNumber>電話號(hào)碼</telephoneNumber>" +
"<mobile>移動(dòng)電話</mobile>" +
"<startTime>用戶的開始生效時(shí)間(YYYY-MM-DD HH:mm:SS)</startTime>" +
"<endTime>用戶結(jié)束生效時(shí)間(YYYY-MM-DD HH:mm:SS) </endTime>" +
"<idCardNumber>身份證號(hào)碼</idCardNumber>" +
"<employeeNumber>工號(hào) </employeeNumber>" +
"<o>用戶所屬的組織的編碼號(hào) </o>" +
"<employeeType>用戶類型</employeeType>" +
"<supporterCorpName>所在公司名稱 </supporterCorpName>" +
"</account>" +
"</accounts>]]>";
//調(diào)用方法
String method = "sayHello";
method = "getUserList";
String data="<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://impl.webservice.platform.hotent.com/\">"+
"<soapenv:Body>"+
"<ser:"+method+">"+
"<arg0>"+ xmlData + "</arg0>"+
"</ser:"+method+">"+
"</soapenv:Body>"+
"</soapenv:Envelope>";
String httpUrl="http://127.0.0.1:8080/xx/service/helloWorld?wsdl";
httpUrl="http://127.0.0.1:8080/xx/service/userOrg?wsdl";
try {
//第一步:創(chuàng)建服務(wù)地址
URL url = new URL(httpUrl);
//第二步:打開一個(gè)通向服務(wù)地址的連接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//第三步:設(shè)置參數(shù)
//3.1發(fā)送方式設(shè)置:POST必須大寫
connection.setRequestMethod("POST");
//3.2設(shè)置數(shù)據(jù)格式:content-type
connection.setRequestProperty("content-type", "text/xml;charset=utf-8");
//3.3設(shè)置輸入輸出,因?yàn)槟J(rèn)新創(chuàng)建的connection沒有讀寫權(quán)限,
connection.setDoInput(true);
connection.setDoOutput(true);
//第四步:組織SOAP數(shù)據(jù),發(fā)送請(qǐng)求
String soapXML = data;
//將信息以流的方式發(fā)送出去
// DataOutputStream.writeBytes將字符串中的16位的unicode字符以8位的字符形式寫到流里面
OutputStream os = connection.getOutputStream();
os.write(soapXML.getBytes());
//第五步:接收服務(wù)端響應(yīng),打印
int responseCode = connection.getResponseCode();
System.out.println("responseCode: "+responseCode);
if(200 == responseCode){//表示服務(wù)端響應(yīng)成功
//獲取當(dāng)前連接請(qǐng)求返回的數(shù)據(jù)流
InputStream is = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String temp = null;
while(null != (temp = br.readLine())){
sb.append(temp);
}
is.close();
isr.close();
br.close();
System.out.println(StringEscapeUtils.unescapeXml(sb.toString())); //轉(zhuǎn)義
System.out.println(sb.toString());
} else { //異常信息
InputStream is = connection.getErrorStream(); //通過getErrorStream了解錯(cuò)誤的詳情,因?yàn)殄e(cuò)誤詳情也以XML格式返回,因此也可以用JDOM來獲取。
InputStreamReader isr = new InputStreamReader(is,"utf-8");
BufferedReader in = new BufferedReader(isr);
String inputLine;
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("d:\\result.xml")));// 將結(jié)果存放的位置
while ((inputLine = in.readLine()) != null)
{
System.out.println(inputLine);
bw.write(inputLine);
bw.newLine();
bw.close();
}
in.close();
}
os.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
// 把xml轉(zhuǎn)義
public static String escapeXml(String xml) {
String newXml = xml.replaceAll("<", "<").replaceAll(">", ">").replaceAll(" ", " ").replaceAll("\"", """);
return newXml;
}
總結(jié)
第一種使用HttpURLConnection調(diào)用的方法,基本不用擔(dān)心什么兼容問題,但是通過xml請(qǐng)求接口,需要自己手動(dòng)拼接xml(一般通過soapui生成,然后在程序中根據(jù)情況拼接),并且返回的數(shù)據(jù)也是xml,還要通過代碼解析,可以說是極其麻煩了。
第二種apache-cxf生成java類調(diào)用的方式,直接調(diào)用生成的類即可訪問接口,非常方便,但是apache-cxf和jdk有兼容問題,如果關(guān)聯(lián)的某個(gè)jar包中的代碼有沖突,就會(huì)遇到痛苦的報(bào)錯(cuò)了。在我的嘗試中,就有一個(gè)Service沖突的問題,網(wǎng)上說需要更改某jar包中的class文件,但是由于項(xiàng)目太過龐大,擔(dān)心會(huì)觸發(fā)其他的問題,所以我只能就此作罷。
重點(diǎn)來了,第三種AXIS的方式, 沒有啥兼容問題的方式了,調(diào)用起來非常簡(jiǎn)便,不需要拼接xml,返回的也只能干凈的數(shù)據(jù),
第四種:
httpclient本人親測(cè)好用。不用引用cxf或AXIS一大堆jar包,比較方便
到此這篇關(guān)于java對(duì)接webservice接口的4種方式總結(jié)的文章就介紹到這了,更多相關(guān)java對(duì)接webservice接口內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring MVC Mybatis多數(shù)據(jù)源的使用實(shí)例解析
項(xiàng)目需要從其他網(wǎng)站獲取數(shù)據(jù),因?yàn)槭桥R時(shí)加的需求,這篇文章主要介紹了Spring MVC Mybatis多數(shù)據(jù)源的使用實(shí)例解析,需要的朋友可以參考下2016-12-12
SpringBoot security安全認(rèn)證登錄的實(shí)現(xiàn)方法
這篇文章主要介紹了SpringBoot security安全認(rèn)證登錄的實(shí)現(xiàn)方法,也就是使用默認(rèn)用戶和密碼登錄的操作方法,本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2023-02-02
springboot中@component注解的使用實(shí)例
這篇文章主要介紹了springboot中@component注解的使用實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03
SpringBoot中的三種應(yīng)用事件處理機(jī)制詳解
在項(xiàng)目開發(fā)中,組件間的松耦合設(shè)計(jì)至關(guān)重要,應(yīng)用事件處理機(jī)制作為觀察者模式的一種實(shí)現(xiàn),允許系統(tǒng)在保持模塊獨(dú)立性的同時(shí)實(shí)現(xiàn)組件間的通信,SpringBoot延續(xù)并增強(qiáng)了Spring框架的事件機(jī)制,提供了多種靈活的事件處理方式,本文給大家介紹了SpringBoot中的三種應(yīng)用事件處理機(jī)制2025-04-04
Java代碼審計(jì)的一些基礎(chǔ)知識(shí)你知道嗎
這篇文章主要介紹了基于Java的代碼審計(jì)功能的基礎(chǔ)知識(shí),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2021-09-09
解決mybatis-plus3.4.1分頁插件PaginationInterceptor和防止全表更新與刪除插件SqlE
這篇文章給大家介紹了在Spring.xml文件中配置mybatis-plus3.4.1分頁插件PaginationInterceptor和防止全表更新與刪除插件SqlExplainInterceptor過時(shí)失效問題解決方案,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2020-12-12
Java開發(fā)框架spring實(shí)現(xiàn)自定義緩存標(biāo)簽
這篇文章主要介紹了Java開發(fā)框架spring實(shí)現(xiàn)自定義緩存標(biāo)簽的詳細(xì)代碼,感興趣的小伙伴們可以參考一下2015-12-12

