Java使用JaxWsDynamicClientFactory和HttpURLConnection两种方式调取webservice的接口

摘要:
方法1.在代理类工厂方法中,您需要获取另一方的接口try{//接口地址//代理工厂JaxWsProxyFactoryBeanjaxWsPoxyFactoryBean=newJaxWsProxy FactoryBean();//设置代理地址wsdlAddress:WSDL地址(http://localhost:8082/ws/services/bank?wsdl)jaxWsProxyFactoryBean
方式1.代理类工厂的方式,需要拿到对方的接口
try {
// 接口地址
// 代理工厂
JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();
// 设置代理地址 wsdlAddress: WSDL地址(http://localhost:8082/ws/services/bank?wsdl)
jaxWsProxyFactoryBean.setAddress(wsdlAddress);
    // 设置接口类型
jaxWsProxyFactoryBean.setServiceClass(ICommonService.class);
// 创建一个代理接口实现
ICommonService cs = (ICommonService) jaxWsProxyFactoryBean.create();
// 数据准备
String userName = "Leftso";
// 调用代理接口的方法调用并返回结果
String result = cs.sayHello(userName);
System.out.println("返回结果:" + result);
} catch (Exception e) {
e.printStackTrace();
}
方式2. 动态调用方式
  //WSDL路径 
  String wsUrl = "http://localhost:8082/ws/services/bank?wsdl" ; //方法名
String method
= "getCaseProve"; JaxWsDynamicClientFactory factory = JaxWsDynamicClientFactory.newInstance(); Client client = factory.createClient(wsUrl); Endpoint endpoint = client.getEndpoint(); QName opName = new QName(endpoint.getService().getName().getNamespaceURI(), method); BindingInfo bindingInfo = endpoint.getEndpointInfo().getBinding(); System.out.println(client); if (bindingInfo.getOperation(opName) == null) { for (BindingOperationInfo operationInfo : bindingInfo.getOperations()) { if (method.equals(operationInfo.getName().getLocalPart())) { opName = operationInfo.getName(); break; } } }
  //请求报文   String xmlInput
= "<Request RequestType="RegInfo"><MachineInfo MachineAccount="1" MachinePassword="1"></MachineInfo><FiterInfo UnitNo="" + unit + "" HouseID="" + houseId + "" RecHouseNum="" + recHouseNum + ""></FiterInfo></Request>";   Object[] res = null; try { res = client.invoke(opName, xmlInput); String xml = (String) res[0]; System.err.println("@@@@@@@@@@@@@@@@@"+xml); } catch (Exception e) { e.printStackTrace(); }
方式2所需jar 百度云盘

  链接:https://pan.baidu.com/s/15UjnqWU3J6Sx6CibizyqFw
  提取码:yjfl

 

 方式3. HttpURLConnection调用方式

第一步(读取配置文件):
public class PropertiesUtil {
    private static final Logger logger = LoggerFactory
            .getLogger(PropertiesUtil.class);
    private static Properties properties = null;
    private static String fileName = "/app.properties";
    static {
        properties = new Properties();
        try {
            properties.load(PropertiesUtil.class.getResourceAsStream(fileName));
        } catch (IOException e) {
            logger.error("加载配置文件失败", e);
        }
    }

    public static Properties getProperties() {
        return properties;
    }

    public static String getProp(String propName) {
        return properties.getProperty(propName);
    }
}


public static Map<String, String> resultInterface(String id,String type, String jsonStr) {
    StringBuilder res = new StringBuilder();
    // 1:创建服务地址
    URL url;
    String resultUserName = PropertiesUtil.getProp("resultUserName");
    String resultPassWord = PropertiesUtil.getProp("resultPassWord");
    Map<String, String> map = new HashMap<String, String>();
    try {
      url = new URL(PropertiesUtil.getProp("resultUrl"));
      // 2:打开到服务地址的一个连接
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      // 3:设置连接参数
      // 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);
      //"{"ANNOUNCEMENT_CODE": "CSGGBH001","ANNOUNCEMENT_CONNECT": "asdfasdfasdfasdfasdfasdfasdfsa","ANNOUNCEMENT_DEADLINE": "20181031","ANNOUNCEMENT_GUID": "71F15848-C296-4A60-883C-223C55E9E8D8","ANNOUNCEMENT_START_TIME": "20181101","ANNOUNCEMENT_TITLE": "公告标题","ANNOUNCEMENT_TYPE": "1","ANNOUNCEMENT_UNIT": "单位","ATTACHMENT_SET_CODE": "123","CANCEL_REASON": "撤销理由","CHANGE_TIME": "20181101","CONTACT_NUMBER": "13333333333","CONTACT_PERSON": "联系人","CREATE_TIME": "20181101","DATA_TIMESTAMP": "20181101154911","EMAIL": "123@qq.com","END_DATE": "20181101","FIELD_NUM": "123","LAND_DISTRICT": "440601","LIAISON_UNIT": "单位","LISTING_DEADLINE": "","LISTING_START_TIME": "","LISTING_TYPE": "0","PLATFORM_CODE": "91441900708017879M","PUBLISHING_TIME": "20181101","PUB_SERVICE_PLAT_CODE": "123707003283632515","RETREAT_TIME": "20181101","SUPPLY_TYPE": "1","UNIFIED_DEAL_CODE": "B01-123707003283632515-20181025-000015-V","UNIT_ADDRESS": "单位地址","URL": "http://www.baidu.com","ZIP_CODE": "215600"}";
      //TDJYGG
      // 4:组织SOAP协议数据,发送给服务端
      String soapXML = "<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">"
          + "       <soap12:Header>                           "
          + "         <root xmlns="http://tempuri.org/">      "
          + "           <UserName>"+resultUserName+"</UserName>           "
          + "           <PassWord>"+resultPassWord+"</PassWord>           "
          + "         </root>                                 "
          + "       </soap12:Header>                          "
          + "       <soap12:Body>                             "
          + "         <Push xmlns="http://tempuri.org/">      "
          + "           <Type>"+type+"</Type>                   "
          + "           <JsonStr>"+jsonStr+"</JsonStr>"
          + "         </Push>                                 "
          + "       </soap12:Body>                            "
          + "     </soap12:Envelope>";
      OutputStream os = connection.getOutputStream();
      os.write(soapXML.getBytes("utf-8"));

      // 5:接收服务端的响应
      int responseCode = connection.getResponseCode();
      if (200 == responseCode) {// 表示服务端响应成功
        InputStream is = connection.getInputStream();
        InputStreamReader isr = new InputStreamReader(is,"utf-8");
        BufferedReader br = new BufferedReader(isr);
        String temp = null;
        while (null != (temp = br.readLine())) {
          res.append(temp);
        }
        
        is.close();
        isr.close();
        br.close();
        String xml = res.toString();
        Document doc = DocumentHelper.parseText(xml); // 将字符串转为XML
        Element rootElt = doc.getRootElement(); // 获取根节点
        //System.out.println("根节点:" + rootElt.getStringValue()); 
        
        Element nameElem = rootElt.element("Body").element("PushResponse").element("PushResult");
        String code = nameElem.element("Code").getTextTrim();
        String description = nameElem.element("Description").getTextTrim();
        map.put("code", code);
        map.put("description", description);
      } else {
        //res.append("调接口异常!");
        map.put("code", "500");
        map.put("description", "数据推送失败,服务端响应失败!");
        logger.error("数据推送失败,服务端响应失败!");
      }
      os.close();
    } catch (Exception e) {
      //res.append("调接口异常!");
      map.put("code", "500");
      map.put("description", "数据推送异常,推送信息为trans_notice表或trans_target表的id>>>>:" + id);
      logger.error("数据推送异常,推送信息为trans_notice表或trans_target表的id>>>>:" + id + "", e);
    }
    
    return map;
  }

免责声明:文章转载自《Java使用JaxWsDynamicClientFactory和HttpURLConnection两种方式调取webservice的接口》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Excel计算时间差(精确到分钟、秒)DirectX 11 编程指南下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

iOS Document Interaction(预览和打开文档) 编程指南

原文:http://developer.apple.com/library/ios/#documentation/FileManagement/Conceptual/DocumentInteraction_TopicsForIOS/Introduction/Introduction.html   关于 DocumentInteraction   iOS支持...

使用jquery刷新当前页面

如何使用jquery刷新当前页面 下面介绍全页面刷新方法:有时候可能会用到 window.location.reload()刷新当前页面. parent.location.reload()刷新父亲对象(用于框架) opener.location.reload()刷新父窗口对象(用于单开窗口) top.location.reload()刷新最顶端对象(用于...

Effective Modern C++:05右值引用、移动语义和完美转发

         移动语义使得编译器得以使用成本较低的移动操作,来代替成本较高的复制操作;完美转发使得人们可以撰写接收任意实参的函数模板,并将其转发到目标函数,目标函数会接收到与转发函数所接收到的完全相同的实参。右值引用是将这两个不相关的语言特性连接起来的底层语言机制,正是它使得移动语义和完美转发成了可能。 23:理解std::move和std::forw...

C#各种辅助类收集(CSharpCommonHelper)

1.IOHelper(FileHelper) 2.XmlHelper 3.DBHelper 4.IISHelper 5.OSHelper(WindowsHelper) 6.SqlserverHelper View Code usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; us...

SHA256加密(登陆注册的-密码加盐)

主要代码: 1 // 盐值 2 String salt = null; 3 String password = user.getPassword(); 4 //加密密码 5 String encryptPassword = null; 6 7 salt...

java虚拟机详细图解9--JVM机器指令集

声明:本文摘抄自:https://blog.csdn.net/u010349169/article/details/50412126 Java虚拟机和真实的计算机一样,运行的都是二进制的机器码;而我们将.java 源代码编译成.class 文件,class文件便是Java虚拟机能够认识的二进制机器码,Java能够识别class文件中的信息和机器指令,进而执...