1. 程式人生 > >webservice--四種客戶端呼叫方式

webservice--四種客戶端呼叫方式

第五步:接收服務端響應,列印

package cn.itcast.mobile.client;

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

/**
 * 
 * <p>Title: HttpClient.java</p>
 * <p>Description:HttpURLConnection呼叫方式</p>
 */
public class HttpClient {

	public static void main(String[] args) throws IOException {
		//第一步:建立服務地址,不是WSDL地址
		URL url = new URL("http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx");
		//第二步:開啟一個通向服務地址的連線
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		//第三步:設定引數
		//3.1傳送方式設定:POST必須大寫
		connection.setRequestMethod("POST");
		//3.2設定資料格式:content-type
		connection.setRequestProperty("content-type", "text/xml;charset=utf-8");
		//3.3設定輸入輸出,因為預設新建立的connection沒有讀寫許可權,
		connection.setDoInput(true);
		connection.setDoOutput(true);

		//第四步:組織SOAP資料,傳送請求
		String soapXML = getXML("15226466316");
		OutputStream os = connection.getOutputStream();
		os.write(soapXML.getBytes());
		//第五步:接收服務端響應,列印
		int responseCode = connection.getResponseCode();
		if(200 == responseCode){//表示服務端響應成功
			InputStream is = connection.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			
			StringBuilder sb = new StringBuilder();
			String temp = null;
			while(null != (temp = br.readLine())){
				sb.append(temp);
			}
			System.out.println(sb.toString());
			
			is.close();
			isr.close();
			br.close();
		}

		os.close();
	}
	
	/**
	 * <?xml version="1.0" encoding="utf-8"?>
<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>string</mobileCode>
      <userID>string</userID>
    </getMobileCodeInfo>
  </soap:Body>
</soap:Envelope>
	 * @param phoneNum
	 * @return
	 */
	public static String getXML(String phoneNum){
		String soapXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
		+"<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>"+phoneNum+"</mobileCode>"
		      +"<userID></userID>"
		    +"</getMobileCodeInfo>"
		  +"</soap:Body>"
		+"</soap:Envelope>";
		return soapXML;
	}
}