• 最原始的java方式-HttpURLConnection-调用WebService


    例子

    package com.itheima.weatherClient;
    
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    public class HttpURLConnectionDemo {
        /**
         * 通过UrlConnection调用Webservice服务
         * @throws Exception 
         *
         */
        public static void main(String[] args) throws Exception {
            //服务地址 注意 这里不是wsdl
            URL wsUrl=new URL("http://ws.webxml.com.cn/WebServices/WeatherWS.asmx");
            
            //获取连接通道
            HttpURLConnection  conn = (HttpURLConnection) wsUrl.openConnection();
            
            
            
            //参数设置
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
            
          //获取网络输出流
              OutputStream os = conn.getOutputStream();
            
            //请求参数
            String city="北京";
            String user="";
            
            //请求体
            String soap ="<?xml version="1.0" encoding="utf-8"?>"
            +"<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">"
                +"<soap:Body>"
        +"<getWeather xmlns="http://WebXml.com.cn/">"
            +"<theCityCode>"+city+"</theCityCode>"
          +"<theUserID>"+user+"</theUserID>"
        +"</getWeather>"
      +"</soap:Body>"
    +"</soap:Envelope>";
            
            //向服务端发送数据
            os.write(soap.getBytes());
            
    
            //等待接收服务端返回的数据
            
            //建立读取流 读取网络返回数据
            InputStream is = conn.getInputStream();
            
            byte[] b=new byte[1024];
            
            int len=0;
            
            StringBuffer sb=new StringBuffer();
            //循环读取,存放数据在b中,然后存放在stringbuf中
            while((len=is.read(b))!=-1){
                String str=new String(b,0,len,"utf-8");
                sb.append(str);
            }
            
            //释放资源
            is.close();
            os.close();
            conn.disconnect();
            
            //显示服务器返回的数据----这里返回的数据也是xml格式的
            System.out.println(sb);
    
        }
    }
  • 相关阅读:
    Keras学习率调整
    机器学习算法的调试---梯度检验(Gradient Checking)
    Python 上下文管理器
    Python垃圾回收机制
    Css 动画的回调
    全新的membership框架Asp.net Identity——绕不过的Claims
    CSS代码重构与优化
    html5 本地存储
    ASP.NET MVC 随想录
    谈谈Angular关于$watch,$apply 以及 $digest的工作原理
  • 原文地址:https://www.cnblogs.com/mlbblkss/p/7000454.html
Copyright © 2020-2023  润新知