1. 程式人生 > >Java呼叫WebService(asmx)服務介面

Java呼叫WebService(asmx)服務介面

匯入httpclient jar

		<dependency>
			<groupId>commons-httpclient</groupId>
			<artifactId>commons-httpclient</artifactId>
			<version>3.1</version>
		</dependency>

1. 利用HttpURLConnection通過soap呼叫介面

public static void cl6(String xml) throws IOException {
		// 伺服器地址
		String urlString = "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx";
		// 需要呼叫的方法
		String soapActionString = "getMobileCodeInfo";
		URL url = new URL(urlString);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		// 拼接soap
		String soap = xml;
		byte[] buf = soap.getBytes("UTF-8");
		// 設定報頭
		conn.setRequestProperty("Content-Length", String.valueOf(buf.length));
		conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
		conn.setRequestProperty("soapActionString", soapActionString);
		conn.setRequestMethod("POST");
		conn.setDoOutput(true);
		conn.setDoInput(true);

		OutputStream out = conn.getOutputStream();
		out.write(buf);
		out.close();
		// 獲取響應狀態碼
		int code = conn.getResponseCode();
		StringBuffer sb = new StringBuffer();
		if (code == HttpStatus.OK.value()) {
			InputStream is = conn.getInputStream();
			byte[] b = new byte[1024];
			int len = 0;
			while ((len = is.read(b)) != -1) {
				String s = new String(b, 0, len, "utf-8");
				sb.append(s);
			}
			is.close();
		}
		System.out.println(sb);
	}

	public static void main(String args[]) throws IOException {
		
		String str = 
					"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
					+ "<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/\">\n"
					+ "  <soap:Body>\n" 
					+ "    <getMobileCodeInfo xmlns=\"http://WebXml.com.cn/\">\n"
					+ "      <mobileCode>18291876713</mobileCode>\n" 
					+ "      <userID></userID>\n"
					+ "    </getMobileCodeInfo>\n" 
					+ "  </soap:Body>\n" 
					+ "</soap:Envelope>";
		
		cl6(str);
	}

2. 使用HttpClient

public static void cl3() throws IOException {
		// 輸入服務網址
		HttpClient client = new HttpClient();
		// HttpClient client = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true));
		// GetMethod
		PostMethod post = new PostMethod("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo");
		// 設定引數
		post.setParameter("mobileCode", "18291876713");
		post.setParameter("userID", "");
		// client.setTimeout(newTimeoutInMilliseconds);

		// 執行,返回一個結果碼
		int code = client.executeMethod(post);

		System.out.println("結果碼:" + code);
		// 獲取xml結果
		String result = post.getResponseBodyAsString();
		System.out.println("結果:" + result);
		// 釋放連線
		post.releaseConnection();
		// 關閉連線
		((SimpleHttpConnectionManager) client.getHttpConnectionManager()).shutdown();
	}