一、基本概念:
WebService,顾名思义就是基于Web的服务。它使用Web(HTTP)方式,接收和响应外部系统的某种请求。从而实现远程调用;
WebService所使用的数据均是基于XML格式的。目前标准的WebService在数据格式上主要采用SOAP协议。SOAP协议实际上就是一种基于XML编码规范的文本协议。
XML : 扩展性标记语言;
WSDL:Web服务描述语言;
SOAP : 简单对象访问协议。SOAP = 在HTTP的基础上+XML数据。
示例代码一:
服务端发布服务:
@WebService
public class HelloServiceImpl implements HelloService{
public String sayHello(String name) {
return "hello: "+name;
}
@WebMethod(exclude=true) //此方法不发布为服务
public String sayNiMa(String name) {
return "fuck: "+name;
}
public static void main(String[] args) {
Endpoint.publish("http://192.168.19.1:1234/helloService", new HelloServiceImpl());
}
}
//查看服务情况: 网址 http://192.168.19.1:1234/helloService?wsdl
客户端调用<一>:
生产客户端代码:
cmd -- >选择盘符 ---> wsimport -s . http://192.168.19.1:1234/helloService?wsdl
public class App {
public static void main(String[] args) {
HelloServiceImplService service = new HelloServiceImplService();
HelloServiceImpl impl = service.getHelloServiceImplPort();
System.out.println(impl.sayHello("王八"));
}
}
客户端调用<二>
使用urlconnection:
public class ConnWeb {
private static final String SERVICEURL = "http://192.168.19.1:1234/helloService";
public static void main(String[] args) throws Exception {
URL conn = new URL(SERVICEURL);
HttpURLConnection httpConn = (HttpURLConnection)conn.openConnection();
//打开输入和输出
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
//设置请求信息
httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
//请求体
StringBuffer sb = new StringBuffer();
sb.append("<soapenv:Envelope ");
sb.append("xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" ");
sb.append("xmlns:q0=\"http://webService.com/\" ");
sb.append("xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" ");
sb.append("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> ");
sb.append("<soapenv:Body><q0:sayHello><arg0>樊三</arg0></q0:sayHello></soapenv:Body> ");
sb.append("</soapenv:Envelope>");
//发送请求
OutputStream os = httpConn.getOutputStream();
os.write(sb.toString().getBytes());
//获取返回值
InputStream is = httpConn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
//返回 XML格式的数据
String result = br.readLine();
//释放资源
br.close();
is.close();
os.close();
httpConn.disconnect();
}
}