1、新建WebService项目
2、配置Tomcat服务器
至此,项目搭建基本完成啦,还需要进行一下设置
如果缺少Tomcat那项的话:
然后,点击运行Tomcat即可
这时候可能会报错,网页也打不开
为啥呢,我们看一下配置
报了一个问题,直接在这解决就行,或者去Artifacts解决,都是一样的
然后重新启动,就能正常跳转至浏览器啦
到这,我们的服务就已经正常发布了
3、搭建客户端
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class ClientOne {
public static void main(String[] args) throws IOException {
//第一步:创建服务地址,不是WSDL地址
URL url = new URL("http://localhost:8080/WebServiceTeach/services/HelloWorld?wsdl");
//第二步:打开一个通向服务地址的连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//第三步:设置参数
//3.1发送方式设置:POST必须大写
connection.setRequestMethod("POST");
//3.2设置数据格式:content-type
connection.setRequestProperty("content-type", "text/xml;charset=UTF-8");
//3.3设置输入输出,因为默认新创建的connection没有读写权限,
connection.setDoInput(true);
connection.setDoOutput(true);
//第四步:组织SOAP数据,发送请求
String soapXML = getXML("济南");
OutputStream os = connection.getOutputStream();
os.write(soapXML.getBytes());
//第五步:接收服务端响应,打印
int responseCode = connection.getResponseCode();
if(200 == responseCode){//表示服务端响应成功
InputStream is = connection.getInputStream();
//将字节流转换为字符流
InputStreamReader isr = new InputStreamReader(is,"utf-8");
//使用缓存区
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String temp = null;
while(null != (temp = br.readLine())){
sb.append(temp);
}
System.out.println(sb.toString());
is.close();
isr.close();
br.close();
}
os.close();
}
//组织数据,将数据拼接一下
public static String getXML(String city){
String soapXML = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:exam=\"http://example/\">\n" +
" <soapenv:Header/>\n" +
" <soapenv:Body>\n" +
" <exam:sayHelloWorldFrom>\n" +
" <!--Optional:-->\n" +
" <arg0>" + city +"</arg0>\n" +
" </exam:sayHelloWorldFrom>\n" +
" </soapenv:Body>\n" +
"</soapenv:Envelope>";
return soapXML;
}
}
XML报文我是在soapUI上面查的