码上敲享录 > java入门知识分享 > 纯java实现webservice服务端和客户端

纯java实现webservice服务端和客户端

上一章章节目录下一章 2019-02-21已有139人阅读 评论(0)

纯java实现webservice服务端和客户端


解决方法:

1.webservice服务端

package com.test;

import javax.jws.WebService;

import javax.xml.ws.Endpoint;

@WebService(targetNamespace="http://webservice.api.com/")

public class WebServiceServer {

   public String getValue(String name){

       return "Hello"+name;

   }

 

   public static void main(String[] args) {

       Endpoint.publish("http://localhost:1008/service/serviceHello", new WebServiceServer());

       System.out.println("发布成功!");

   }

}


2.客户端

package com.test;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.HttpURLConnection;

import java.net.URL;


public class WebServiceClient {


   public static void main(String[] args) throws Exception {

       //服务的地址

       URL wsUrl = new URL("http://localhost:1008/service/serviceHello");

       HttpURLConnection conn = (HttpURLConnection) wsUrl.openConnection();

       conn.setDoInput(true);

       conn.setDoOutput(true);

       conn.setRequestMethod("POST");

       conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");

       OutputStream os = conn.getOutputStream();

       //请求体

       String soap = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:q0=\"http://webservice.api.com/\" xmlns:xsd=


\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" +

                     "<soapenv:Body> <q0:getValue><arg0>aaa</arg0>  </q0:getValue> </soapenv:Body> </soapenv:Envelope>";

       os.write(soap.getBytes());

       InputStream is = conn.getInputStream();

       byte[] b = new byte[1024];

       int len = 0;

       String s = "";

       while((len = is.read(b)) != -1){

           String ss = new String(b,0,len,"UTF-8");

           s += ss;

       }

       System.out.println(s);

       is.close();

       os.close();

       conn.disconnect();

   }

}


0

有建议,请留言!

  • *您的姓名:

  • *所在城市:

  • *您的联系电话:

    *您的QQ:

  • 咨询问题:

  • 提 交