Java中使用POST方式调用webservice接口的方法

2019-06-23 18:33 阅读 131 次 评论 0 条

Java中使用POST方式调用webservice的代码如下(项目代码,做记录):

public String callService(String serviceName, Map<String, String> paramMap)
        throws Exception {
        StringBuffer sBuffer = new StringBuffer();
	sBuffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
	sBuffer.append("<request>");
	// 请求报文默认添加ReqTime,ReqIP,ReqUserID三个必须字段
	// 参数:申请时间
	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	sBuffer.append("<ReqTime>" + df.format(new Date()) + "</ReqTime>");

	// 参数:申请终端IP
	InetAddress address = InetAddress.getLocalHost();
	sBuffer.append("<ReqIP>" + address.getHostAddress() + "</ReqIP>");

	// 参数:申请人ID
	sBuffer.append("<ReqUserID>" + "103" + "</ReqUserID>");

	// 其他参数设置
	for (Map.Entry<String, String> entry : paramMap.entrySet()) {
	    sBuffer.append("<" + entry.getKey() + ">" + entry.getValue() + "</" + entry.getKey() + ">");
	}
	sBuffer.append("</request>");

    try {
        URL url = new URL("http://196.196.196.186:8078/WebServiceMethod.asmx" + "/" + serviceName);
	HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
	conn.setRequestProperty("Content-Length", "0");
	conn.setRequestMethod("POST");
	conn.setUseCaches(false);
	conn.setDoInput(true);
	conn.setDoOutput(true);
	conn.setConnectTimeout(30000);
	conn.setReadTimeout(30000);

	DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
	dos.write(("InfoXML=" + sBuffer.toString()).getBytes("utf-8"));
	dos.flush();

	// 返回数据
	BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
	String line = "";

	// 存放请求内容
	StringBuffer xml = new StringBuffer();
	while ((line = br.readLine()) != null) {
	    xml.append(line);
	}
	dos.close();
	br.close();

	// 解析报文,字符串转XML
	Document document = XMLHelp.getDocumentInstanceFromXmlString(xml.toString().replace("&lt;", "<")
			.replace("&gt;", ">").replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>", ""));
	document.setXMLEncoding("utf-8");

	Element root = document.getRootElement();
	Element resresult = root.element("response");
	Element rtnresult = resresult.element("returnresult");
	String returncode = rtnresult.elementTextTrim("returncode");
	String errormsg = rtnresult.elementTextTrim("errormsg");
	if (returncode == "0") { // 查询失败
	    log.error("HIS WebService接口" + serviceName + "查询失败:" + errormsg);
	    return returncode;
	} else {
	    Element dataresult = resresult.element("data");
	    return dataresult.asXML();
	}
    } catch (Exception e) {
	e.printStackTrace();
	throw new Exception("HIS WebService接口" + serviceName + "调用异常");
    }
}

版权声明:本文著作权归原作者所有,欢迎分享本文,谢谢支持!
转载请注明:Java中使用POST方式调用webservice接口的方法 | 猿笔记
分类:JAVA, 程序笔记 标签:, ,

发表评论


表情