import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.PostMethod; /**調用第三方的webservice服務 ,獲取電話號碼信息 * */ public class MobileCodeService { //1. http-get方式訪問webservice public void get(String mobileCode ,String userID ) throws Exception{ URL url=new URL("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo?mobileCode="+mobileCode+ "&userID="+userID); HttpURLConnection conn=(HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){ //結果碼=200 InputStream is=conn.getInputStream(); //內存流 , ByteArrayOutputStream boas=new ByteArrayOutputStream(); byte[] buffer=new byte[1024]; int len=-1; while((len=is.read(buffer))!=-1){ boas.write(buffer, 0, len); } System.out.println("GET請求獲取的數據:"+boas.toString()); boas.close(); is.close(); } } //2.Post請求 :經過Http-Client 框架來模擬實現 Http請求 public void post(String mobileCode ,String userID) throws Exception{ /**HttpClient訪問網絡的實現步驟: * 1. 準備一個請求客戶端:瀏覽器 * 2. 準備請求方式: GET 、POST * 3. 設置要傳遞的參數 * 4.執行請求 * 5. 獲取結果 */ HttpClient client=new HttpClient(); PostMethod postMethod=new PostMethod("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo"); //3.設置請求參數 postMethod.setParameter("mobileCode", mobileCode); postMethod.setParameter("userID", userID); //4.執行請求 ,結果碼 int code=client.executeMethod(postMethod); //5. 獲取結果 String result=postMethod.getResponseBodyAsString(); System.out.println("Post請求的結果:"+result); } //2.Post請求 :經過Http-Client 框架來模擬實現 Http請求 public void soap() throws Exception{ HttpClient client=new HttpClient(); PostMethod postMethod=new PostMethod("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx"); //3.設置請求參數 postMethod.setRequestBody(new FileInputStream("D:/soap.xml")); //修改請求的頭部 postMethod.setRequestHeader("Content-Type", "text/xml; charset=utf-8"); //4.執行請求 ,結果碼 int code=client.executeMethod(postMethod); System.out.println("結果碼:"+code); //5. 獲取結果 String result=postMethod.getResponseBodyAsString(); System.out.println("Post請求的結果:"+result); } public static void main(String[] args) throws Exception{ MobileCodeService ws=new MobileCodeService(); ws.get("15958083603", ""); ws.post("15958012349", ""); ws.soap(); } }