最原始的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); } }