
【工程截图】注意:无需使用Wsimport生成客户端代码
【HttpClient.java】
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL; public class HttpClient { public static void main(String[] args) throws IOException { //开启 一个http链接
//webservice地址
URL url = new URL("http://127.0.0.1:12345/weather"); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); //设置post请求,post是大写
httpURLConnection.setRequestMethod("POST");
//Content-Type: text/xml; charset=utf-8
httpURLConnection.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); //设置请求和响应
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true); String requestString = requestString("郑州");
//发送soap协议
httpURLConnection.getOutputStream().write(requestString.getBytes()); //接收响应内容 InputStream inputStream = httpURLConnection.getInputStream(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); int len=-1;
byte[] b = new byte[1024];
//将inputStream内容写到byteArrayOutputStream
while((len= inputStream.read(b, 0, 1024))!=-1){
byteArrayOutputStream.write(b, 0, len);
} //获取响应内容
String responseString = byteArrayOutputStream.toString(); System.out.println(responseString); //解析响应的xml数据。
//....
inputStream.close();
byteArrayOutputStream.close();
} /**
<?xml version="1.0" ?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<ns2:queryWeather xmlns:ns2="http://server.weather.jaxws.Higgin.com/">
<arg0>郑州</arg0>
</ns2:queryWeather>
</S:Body>
</S:Envelope>
*/
//soap协议内容,请求的 内容
private static String requestString(String cityName){
String xmlString = "<?xml version=\"1.0\" ?>" +
"<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<S:Body>" +
"<ns2:queryWeather xmlns:ns2=\"http://server.weather.jaxws.Higgin.com/\">" +
"<arg0>"+cityName+"</arg0>" +
"</ns2:queryWeather>" +
"</S:Body>" +
"</S:Envelope>";
return xmlString;
}
}
【运行结果】
(注意:要先开启WebService服务)
(需要进一步解析出自己所需的数据,使用正则表达式)