package test.xt.hb.map;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class CallByHttp {

	private static String actionBySOAP() {
		StringBuilder sb = new StringBuilder();
		sb.append("<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" "
				+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">");
		sb.append("<SOAP-ENV:Body>");
		sb.append("<m:getWeatherbyCityName xmlns:m=\"http://WebXml.com.cn/\">");
		sb.append("<m:theCityName>58367</m:theCityName>");
		sb.append("</m:getWeatherbyCityName>");
		sb.append("</SOAP-ENV:Body>");
		sb.append("</SOAP-ENV:Envelope>");
		return sb.toString();
	}

	private static String callWebService(String wsdl) throws Exception {
		System.setProperty("sun.net.client.defaultConnectTimeout", "20000");
		System.setProperty("sun.net.client.defaultReadTimeout", "20000");
		// URL连接
		URL url = new URL(wsdl);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		// conn.setRequestMethod("GET");
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Length", String.valueOf(actionBySOAP().getBytes().length));
		conn.setRequestProperty("Content-Type", "text/xml; charset=GBK");
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setConnectTimeout(20000);
		// 请求输入内容
		OutputStream output = conn.getOutputStream();
		output.write(actionBySOAP().getBytes());
		output.flush();
		output.close();
		// 请求返回内容
		InputStreamReader isr = new InputStreamReader(conn.getInputStream());
		BufferedReader br = new BufferedReader(isr);
		StringBuilder sb = new StringBuilder();
		String str = null;
		while ((str = br.readLine()) != null) {
			sb.append(str + "\n");
		}
		br.close();
		isr.close();
		return sb.toString();
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		String WSDL = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?WSDL";
		String result = callWebService(WSDL);
		System.out.println(result);
	}
}