80,351
社区成员
发帖
与我相关
我的任务
分享
SOAP 请求
--------------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Header/>
<S:Body>
<ns2:add xmlns:ns2="http://service/">
<num1>3</num1>
<num2>4</num2>
</ns2:add>
</S:Body>
</S:Envelope>
--------------------------------------------------------------------------------
SOAP 响应
--------------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<ns2:addResponse xmlns:ns2="http://service/">
<return>7</return>
</ns2:addResponse>
</S:Body>
</S:Envelope>
InputStream inStream;
inStream = getAssets().open("test.xml");
String soap = readSoapFile(inStream, num1,num2);
byte[] data = soap.getBytes();
// 提交Post请求
URL url = new URL("http://10.93.136.5:8082/WebService/MyTestService");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(5 * 1000);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
OutputStream outStream = conn.getOutputStream();
outStream.write(data);
outStream.flush();
outStream.close();
if (conn.getResponseCode() == 200)
{
// 解析返回信息
return parseResponseXML(conn.getInputStream());
}
private String readSoapFile(InputStream inStream, String num1, String num2) throws Exception
{
// 从流中获取文件信息
byte[] data = readInputStream(inStream);
String soapxml = new String(data);
// 占位符参数
Map<String, String> params = new HashMap<String, String>();
params.put("param1", num1);
params.put("param2", num2);
// 替换文件中占位符
return replace(soapxml, params);
}
private byte[] readInputStream(InputStream inputStream) throws Exception
{
byte[] buffer = new byte[1024];
int len = -1;
ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1)
{
outSteam.write(buffer, 0, len);
}
outSteam.close();
inputStream.close();
return outSteam.toByteArray();
}
private String replace(String xml, Map<String, String> params) throws Exception
{
String result = xml;
if (params != null && !params.isEmpty())
{
for (Map.Entry<String, String> entry : params.entrySet())
{
String name = "\\$" + entry.getKey();
Pattern pattern = Pattern.compile(name);
Matcher matcher = pattern.matcher(result);
if (matcher.find())
{
result = matcher.replaceAll(entry.getValue());
}
}
}
return result;
}
<?xml version="1.0" encoding="UTF-8"?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Header/>
<S:Body>
<ns2:add xmlns:ns2="http://service/">
<num1>$param1</num1>
<num2>$param2</num2>
</ns2:add>
</S:Body>
</S:Envelope>