package cn.hmsoft.skill.helper;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import cn.hmsoft.helper.StringHelper;

public class WebServiceHelper {

	/********************************
	 * 调用WebService
	 */
	public static String callWebService(String url, String xmlns, String requestBody) {
		try {
			URL wsUrl = new URL(url);
			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();

			// 请求体//xmlns:hbea=\"http://hbea.edu.cn/
			String soap = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" "
					+ (StringHelper.isEmpty(xmlns) ? "" : xmlns.trim()) + "><soapenv:Header/><soapenv:Body>"
					+ (StringHelper.isEmpty(requestBody) ? "" : requestBody.trim())
					+ "</soapenv:Body></soapenv:Envelope>";

			os.write(soap.getBytes());
			os.flush();

			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;
			}

			is.close();
			os.close();
			conn.disconnect();
			return s;
		} catch (Exception e) {
			// e.printStackTrace();
			return null;
		}
	}
}
