package com.zhw.test;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.xml.bind.DatatypeConverter;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.xpath.DefaultXPath;
public class Test20 {
public static void main(String[] args) throws IOException, DocumentException {
StringBuffer result = null;
//此地址为别人提供的地址(替换即可)
String urlString = "http://xxxxx:8000/sap/bc/srt/rfc/sap/d_010/500/d_11111/zsd_11111?sap-client=500";
URL url = new URL(urlString);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
System.out.println(httpConn);
//拼接请求体(注意拼接请求参数xml的时候一定根据提供的格式拼接,""的地方要用转义字符隔开\)
String soap="
"
+"
+"
+" "
+"
+" "
+"
+"
+"
+"
+"
+"
+"
+"
+"
+""
+" "
+" "
+"
+" "
+"
+"
+"
+" "
+" "
+" "
+" "
+"";
byte[] buf = soap.getBytes();
//设置一些头参数
httpConn.setRequestProperty("Content-Length", String.valueOf(buf.length));
httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
//用户授权不然(401未授权)
String encoding = DatatypeConverter.printBase64Binary(("COMzjj:admin1234").getBytes("UTF-8"));
httpConn.setRequestProperty("Authorization", "Basic " + encoding);
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
OutputStream out = httpConn.getOutputStream();
out.write(buf);
out.close();
System.out.println(out);
System.out.println("HTTP Response code is " + httpConn.getResponseCode());
InputStreamReader isr = new InputStreamReader(
httpConn.getInputStream(), "utf-8");
BufferedReader inReader = new BufferedReader(isr);
System.out.println("返回数据:"+inReader);
String inputLine;
result = new StringBuffer();
while ((inputLine = inReader.readLine()) != null) {
result.append(inputLine);
}
//获取返回的soap型消息xml数据
System.out.println(result);
//下面利用 dom4j的只是来解析这个xml
Document doc = DocumentHelper.parseText(result.toString());
//找到所取参数的节点//+节点的名字
DefaultXPath xpath = new DefaultXPath("//CREDITEXPOSURE");
//找到该节点的命名空间xmlns:后面的两个参数
xpath.setNamespaceURIs(Collections.singletonMap("n0","urn:sap-com:document:sap:rfc:functions"));
List list = xpath.selectNodes(doc);
//遍历结果找到节点里面的内容(迭代器遍历)
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
Element node = (Element) iterator.next();
System.out.println("获取到的节点上的数据:"+node.getText());
}
}
}
下面是控制台的打印结果:
(post请求参数的request)
HTTP Response code is 200(200为成功,401为未授权没有进行用户名密码校验,500为没有该服务检查下url地址的正确性)
返回数据:java.io.BufferedReader@b97cf78
(post请求返回的报文response)
(最后解析得到所需要的数据)
获取到的节点上的数据:0.0