天天看點

三、通過UrlConnection調用Webservice服務

1、接着學習調用WebService服務的第三種方法,通過UrlConnection調用Webservice服務。

2、還是一樣,必須啟動一個WebService服務,代碼:

package com.wang.webservice.service;

import javax.jws.WebService;
import javax.xml.ws.Endpoint;

@WebService
public class HelloService {
	
	public String sayHello( String name ){
		System.out.println(name);
		return "hello " + name;
	}
	
	public static void main(String[] args) {
		Endpoint.publish("http://127.0.0.1:1234/helloservice", new HelloService());
	}
	
}
           

 與上一篇文章用的WebService服務端一樣。啟動,

3、編寫用戶端代碼:

package com.wang.webservice.urlconnection;

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

/*
 * 通過UrlConnection調用Webservice服務
 */
public class App {
	
	public static void main(String[] args) {
		URL wsUrl = null;
		try {
			
			wsUrl = new URL("http://127.0.0.1:1234/helloservice");
			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://service.webservice.wang.com/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
					    + "<soapenv:Body><q0:sayHello><arg0>tom</arg0></q0:sayHello></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();
			
		} catch (MalformedURLException e) {
			System.out.println("建立URL失敗");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("URL打開失敗");
			e.printStackTrace();
		}
		
	}
	
}
           

 這裡面注解中的請求體和傳回體,在上一篇文章中介紹了,這裡不再重複,

運作後,調用WebService服務端成功。這種方法更底層一些;

繼續閱讀