当前位置:首页 » 《资源分享》 » 正文

java对接webservice接口的4种方式

19 人参与  2024年05月11日 18:32  分类 : 《资源分享》  评论

点击全文阅读


一、使用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("<", "&lt;").replaceAll(">", "&gt;").replaceAll(" ", " ").replaceAll("\"", "&quot;");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);

点击全文阅读


本文链接:http://zhangshiyu.com/post/107145.html

<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1