WebService 通用接收方法

/**
* @Title: getNetStatusRequest
* @Description: TODO(2.1检查网络状态字符串)
* @param:
* @return: String
* @throws
*/

/*拼接xml字符串用,里面域名和参数需要根据具体需求进行修改*/
private static String getSOAPRequest(String information){
StringBuilder sb = new StringBuilder();
sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+ "<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/\">"
+"<soap:Body>"+"******"+
"</soap:Body></soap:Envelope>");
return sb.toString();
}

/*得到流*/

public static InputStream getSoapInputStream(String infor){
try {
String soap = getSOAPRequest(infor);
URL url = new URL(
"http://service.smart-health.cn/DeviceWebService.asmx");
URLConnection conn = url.openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Length",
Integer.toString(soap.length()));
conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");

conn.setRequestProperty("SOAPAction",
"域名");
OutputStream os = conn.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "utf-8");
osw.write(soap);
osw.flush();
osw.close();
// 获取webserivce返回的流
InputStream is = conn.getInputStream();
return is;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

 

/*根据流获取需要内容*/

public static String getHealth(String healthInfor){
try {
Document doc;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
InputStream is = getSoapInputStream(healthInfor);
doc = db.parse(getSoapInputStream(healthInfor));
NodeList nl = doc.getElementsByTagName("包含特殊内容的标签名");
StringBuffer sb = new StringBuffer();
for (int count = 0; count < nl.getLength(); count++) {
Node n = nl.item(count);
if(n.hasChildNodes()){
if (n.getFirstChild().getNodeValue().isEmpty()) {
sb = new StringBuffer("#");
break;
}
// 解析并以"#"为分隔符,拼接返回结果
sb.append(n.getFirstChild().getNodeValue() + "#");
}else{
sb.append("对不起,没有您的健康数据!#"+ConvertUtil.convertStreamToString(getSoapInputStream(healthInfor)));
}
}
is.close();
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

posted @ 2017-01-10 09:49  泥猴桃\n  阅读(351)  评论(0编辑  收藏  举报