作者:刺猬xiaojie | 来源:互联网 | 2023-10-12 16:49
基于SOAP协议的WEB服务调用方法:
importorg.Apache.com mons.lang.stringescapeutils;
import org.apache.log4j.Logger;
//*
*web服务请求
* @param xmlStr
* @return
* @throws Exception
*/
publicstaticstringcallxml (字符串xmlstr,字符串soap地址) throws IOException {
//地址
URL URL=newurl (soap地址;
//调用方法
String soapActiOnString=' ';
logger.info ('请求soap地址: ' soap地址);
logger.info (要求' soap action:' soap action string );
//打开链接
httpurlcOnnectioncon=(httpurl connection ) url.openConnection );
logger.info ('请求消息: ' xmlStr );
设置头部信息
con.setrequestmethod(post );
con.setrequestproperty (' content-type ',' text/xml; charset=UTF-8 ';
con.setrequestproperty (' content-length ',string.valueof ) xmlstr.getbytes ).length );
con.setrequestproperty (' soap action ',soapActionString );
//post请求需要设置
con.setdooutput(true;
con.setdoinput(true;
//向请求body写入xml以设置请求参数。
打印机写入器out=null;
byte[] respOnseData=null;
bytearrayoutputstreambaos=newbytearrayoutputstream (;
try {
out=new printwriter (newoutputstreamwriter (con.get output stream )、' utf-8 ' )
//发送请求参数
out.print(xmlstr;
out.flush (;
//设置响应返回的信息
inputstream IPS=con.get inputstream (;
byte[] buf=new byte[1024];
int length=0;
while((Length=IPS.read ) ) buf )!=-1 ()
BaoS.write(buf,0,length );
baos.flush (;
}
respOnseData=baos.toByteArray (;
}catch(ioexceptione ) {
thrownewioexception(e;
} finally {
if (出局!=空) {
out.close (;
}
try {
baos.close (;
}catch(ioexceptione ) {
thrownewioexception(e;
}
con.disconnect (;
}
//处理写入响应信息
stringrespOnsemess=new string (响应数据,' utf-8 ';
响应消息=stringescapeutils.unescape html (响应消息);
logger.info ('响应代码: ' con.getresponse代码) );
logger.info (响应消息:“响应消息”);
返回响应消息;
}
标签:呼叫、Java、web服务、请求、new、xmlStr、con、out、String
资料来源: https://www.cn blogs.com/benben cyb/p/14468786.html