webService学习记录-02

客户端调用webService方法:

1.wsimport方法调用,前面已经说过。

2.ajax方法调用:此方法没有很好的理解,简单的了解下。

3.通过UrlConnection调用。

package cn.itcast.ws.urlConnection;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class App {

	/**
	 * @param args
	 * @throws MalformedURLException 
	 */
	public static void main(String[] args) throws Exception {
		
		//服务的地址
		URL wsUrl = new URL("http://127.0.0.1:6789/hello");
		
		HttpURLConnection conn = (HttpURLConnection) wsUrl.openConnection();
	    conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
		
		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Type", "text/xml;charset =  UtF-8");
		
		OutputStream os = conn.getOutputStream();
		String soap = "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
				+ "<soap:Body><getMobileCodeInfo xmlns=\"http://WebXml.com.cn/\"><mobileCode>13436823445</mobileCode><userID></userID>"
				+ "</getMobileCodeInfo></soap:Body></soap:Envelope>";
		
		os.write(soap.getBytes());
		
		InputStream is  = conn.getInputStream();
		
		byte[] b = new byte[1024];
		String s = "";
		int len = 0;
		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();
	}

}


这段代码执行的时候,后台报错,暂时未发现原因,出现的错误为:

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 500 for URL: http://127.0.0.1:6789/hello
	at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
	at cn.itcast.ws.urlConnection.App.main(App.java:35)


4.客户端编程的方式调用webService服务


将之前客户端生成的客户端代码中服务接口类拷贝到项目中,HelloService.java

然后创建java类编写客户端代码:

package cn.itcast.ws.client;

import java.net.URL;

import javax.xml.namespace.QName;
import javax.xml.ws.Service;



/**
 * 通过客户端编程的方式调用webService服务
 * @author wangz_ing
 *
 */
public class App {


	public static void main(String[] args) throws Exception {
		URL wsdlUrl = new URL("http://127.0.0.1:6789/hello?wsdl");
		Service s = Service.create(wsdlUrl, new QName("http://ws.itcast.cn/","HelloServiceService"));
		HelloService hs = s.getPort(new QName("http://ws.itcast.cn/","HelloServicePort"), HelloService.class);
		String ret = hs.sayHello("aa");
		System.out.println(ret);

	}

}

类中的所有参数均从wsdl文件中获取,因此需要对阅读wsdl文件比较熟悉

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值