Java 调用远程webservice接口实例(SOAP方式,DOM分析XML)

package myweather;

import java.io.*;
import java.net.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import javax.swing.JOptionPane;

public class MyWeather {
private static String getSoapRequest(String city) {
try {
InputStreamReader isr = new InputStreamReader(new FileInputStream("weather.xml"));
BufferedReader reader = new BufferedReader(isr);
String soap = "";
String tmp;
while ((tmp = reader.readLine()) != null) {
soap += tmp;
}
reader.close();
isr.close();
return soap.replace("${city}$", city);
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
private static InputStream getSoapInputStream(String city)throws Exception
{
try
{
String soap =getSoapRequest(city);
if(soap==null)
{
return null;
}
URL url=new URL("http://www.webxml.com.cn/WebServices/WeatherWebService.asmx");
URLConnection conn=url.openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);

conn.setRequestProperty("Content-Length", Integer.toString(soap.length()));
conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
conn.setRequestProperty("SOAPAction","http://WebXml.com.cn/getWeatherbyCityName");

OutputStream os=conn.getOutputStream();
OutputStreamWriter osw=new OutputStreamWriter(os,"utf-8");
//osw.write(new String(soap.getBytes(),"utf-8"));
osw.write(soap);
osw.flush();
osw.close();

InputStream is=conn.getInputStream();
return is;
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
}
public static String getWeather(String city)
{
try
{
Document doc;
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db=dbf.newDocumentBuilder();
InputStream is=getSoapInputStream(city);
doc=db.parse(is);
NodeList nl=doc.getElementsByTagName("getWeatherbyCityNameResult");
Node n=nl.item(0);
//JOptionPane.showMessageDialog(null,n.getChildNodes().getLength());
for (int i=0;i<n.getChildNodes().getLength()-1;i++)
{
String weather=n.getChildNodes().item(i).getTextContent();
System.out.print(weather);
}
is.close();
return "null";
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
}
public static void main (String [] args )throws Exception
{
//System.out.println(MyWeather.getWeather("上海"));
MyWeather.getWeather("广州");
}

}


//将以下XML保存为weather.xml

/*XML:<?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>
<getWeatherbyCityName xmlns="http://WebXml.com.cn/">
<theCityName>${city}$</theCityName>
</getWeatherbyCityName>
</soap:Body>
</soap:Envelope>*/
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值