首页 > 基础资料 博客日记
java对接webservice接口的4种方式
2023-12-26 21:30:23基础资料围观260次
本篇文章分享java对接webservice接口的4种方式,对你有帮助的话记得收藏一下,看Java资料网收获更多编程知识
一、使用httpclient的方式调用
JaxWsDynamicClientFactory factory = JaxWsDynamicClientFactory.newInstance();
// 创建客户端连接
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");//如果有命名空间需要加上这个,第一个参数为命名空间名称,调用的方法名称
res = client.invoke(operationName, "admin");//后面为WebService请求参数数组
System.out.println(res[0]);
}catch (Exception e) {
e.printStackTrace();
}
第二种方法
// 被<![CDATA[]]>这个标记所包含的内容将表示为纯文本
String xmlData = "<![CDATA[<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<accounts>" +
"<account>" +
"<accId>帐号ID(必填)</accId>" +
"<userPasswordMD5>密码</userPasswordMD5>" +
"<userPasswordSHA1>密码</userPasswordSHA1>" +
"其中userPasswordSHA1标签代表SHA1加密后的密码,userPasswordMD5标签代表MD5加密后的密码" +
"<name>姓名</name>" +
"<sn>姓</sn>" +
"<description>描述 </description>" +
"<email>邮箱 </email>" +
"<gender>性别</gender>" +
"<telephoneNumber>电话号码</telephoneNumber>" +
"<mobile>移动电话</mobile>" +
"<startTime>用户的开始生效时间(YYYY-MM-DD HH:mm:SS)</startTime>" +
"<endTime>用户结束生效时间(YYYY-MM-DD HH:mm:SS) </endTime>" +
"<idCardNumber>身份证号码</idCardNumber>" +
"<employeeNumber>工号 </employeeNumber>" +
"<o>用户所属的组织的编码号 </o>" +
"<employeeType>用户类型</employeeType>" +
"<supporterCorpName>所在公司名称 </supporterCorpName>" +
"</account>" +
"</accounts>]]>";
//调用方法
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 {
//第一步:创建服务地址
URL url = new URL(httpUrl);
//第二步:打开一个通向服务地址的连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//第三步:设置参数
//3.1发送方式设置:POST必须大写
connection.setRequestMethod("POST");
//3.2设置数据格式:content-type
connection.setRequestProperty("content-type", "text/xml;charset=utf-8");
//3.3设置输入输出,因为默认新创建的connection没有读写权限,
connection.setDoInput(true);
connection.setDoOutput(true);
//第四步:组织SOAP数据,发送请求
String soapXML = data;
//将信息以流的方式发送出去
// DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写到流里面
OutputStream os = connection.getOutputStream();
os.write(soapXML.getBytes());
//第五步:接收服务端响应,打印
int responseCode = connection.getResponseCode();
System.out.println("responseCode: "+responseCode);
if(200 == responseCode){//表示服务端响应成功
//获取当前连接请求返回的数据流
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())); //转义
System.out.println(sb.toString());
} else { //异常信息
InputStream is = connection.getErrorStream(); //通过getErrorStream了解错误的详情,因为错误详情也以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")));// 将结果存放的位置
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转义
public static String escapeXml(String xml) {
String newXml = xml.replaceAll("<", "<").replaceAll(">", ">").replaceAll(" ", " ").replaceAll("\"", """);
return newXml;
}
二、使用HttpURLConnection的方式调用
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请求接口
printOut.flush();
printOut.close();
// 从连接的输入流中取得回执信息
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")));
//从对方的节点中取的返回值(节点名由对方接口指定)
String returnState = d.getElementsByTagName("ReturnStatus").item(0).getFirstChild().getNodeValue();
三、使用AXIS调用WebService
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;
public static void main(String[] args) {
String result = "";
String url = "http://127.0.0.1/uapws/service/nc65to63projectsysplugin";//这是接口地址,注意去掉.wsdl,否则会报错
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress(url);
String parametersName = "string";//设置参数名
call.setOperationName("receiptProject");//设置方法名
call.addParameter(parametersName, XMLType.XSD_STRING, ParameterMode.IN);//方法参数,1参数名、2参数类型、3.入参
call.setReturnType(XMLType.XSD_STRING);//返回类型
String str = json;
Object resultObject = call.invoke(new Object[] { str });//调用接口
result = (String) resultObject;
}
四、使用apache-cxf生成java类调用(不建议)
下载apache-cxf,并配置环境变量,详细说明,请自行学习
String result = "";
NC65To63ProjectService service = new NC65To63ProjectService();
NC65To63ProjectServicePortType servicePort = service.getNC65To63ProjectServiceSOAP11PortHttp();
result = servicePort.receiptProject(json);
文章来源:https://blog.csdn.net/qq_49641620/article/details/134690565
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!
标签: