java调用webservice

java调用webservice


package com;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

public class InvokeWS {
public static void main(String[] args) {
try {
//以请求天气service为例
String point ="http://www.webxml.com.cn/WebServices/WeatherWebService.asmx";
//初始化请求传送的soap信息 soap格式从上面网站可以查到
String soap = getSoapBody("重庆");
//获取 建立至webservice节点的连接
URL url = new URL(point);
URLConnection con = url.openConnection();
con.setUseCaches(false);
con.setDoInput(true);
con.setDoOutput(true);
//设置请求header信息
con.setRequestProperty("Content-Type", "text/xml; charset=gbk");
con.setRequestProperty("Content-Length",String.valueOf(soap.length()));
con.setRequestProperty("SOAPAction", "http://WebXml.com.cn/getWeatherbyCityName");
//发送请求内容 soap至服务端
OutputStream out = con.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(out,"gbk");
writer.write(soap);
writer.flush();
writer.close();
//获取响应信息
InputStream in = con.getInputStream();
InputStreamReader reader = new InputStreamReader(in,"utf-8");
BufferedReader br = new BufferedReader(reader);
String str = br.readLine();
while(str !=null){
System.out.println(str);
str = br.readLine();
}
} catch (Exception e) {
e.printStackTrace();
}
}

private static String getSoapBody(String name){
StringBuffer sb = new StringBuffer();
sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
sb.append("<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/\">");
sb.append("<soap:Body>");
sb.append("<getWeatherbyCityName xmlns=\"http://WebXml.com.cn/\">");
sb.append("<theCityName>").append(name).append("</theCityName>");
sb.append("</getWeatherbyCityName>");
sb.append("</soap:Body>");
sb.append("</soap:Envelope>");
return sb.toString();
}
}

原文地址:https://www.cnblogs.com/zhanggaosong/p/3014255.html