使用URLConnection调用webservice与使用ajax调用webservice的主要的差别就在于前者是使用java语言来构造http请求,
而后者则是使用js语言来构造http请求。这两种方式所实现的功能其实是一样的,只是实现的形式不同而已
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.net.HttpURLConnection;
- import java.net.URL;
- public class App {
- public staticvoid main(String[] args) throws Exception {
- URL wsUrl = new URL("http://127.0.0.1:6790/hello");
- HttpURLConnection conn = (HttpURLConnection) wsUrl.openConnection();
- conn.setDoInput(true);//有输入
- conn.setDoOutput(true);//有输出
- conn.setRequestMethod("POST");
- conn.setRequestProperty("Content-Type","text/xml;charset=utf-8");
- //要想在双引号中再使用双引号,则可以使用转义符\将双引号转义
- String soap = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:q0=\"http://webservice.njupt.com/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"+
- "<soapenv:Body><q0:sayHello><arg0>焦雅琴 我爱你哦 </arg0> </q0:sayHello></soapenv:Body></soapenv:Envelope>";
- OutputStream os = conn.getOutputStream();
- os.write(soap.getBytes());
- InputStream is = conn.getInputStream();
- byte[] b = newbyte[1024];
- int len = 0;
- String s = "";
- while( (len = is.read(b)) != -1){
- s += new String(b,0,len,"UTF-8");
- }
- System.out.println(s);
- os.close();
- is.close();
- conn.disconnect();
- }
- }