Web Service 系列一

一、基本概念:

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();
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值