客户端调用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文件比较熟悉