Springboot调用WebService(asmx)服务接口
导入httpclient jar
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
1. 利用HttpURLConnection通过soap调用接口
public static void test() {
String xml =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
+ "<soap:Envelope">\n"
+ " <soap:Body>\n"
+ " <GetLeave xmlns=\"http://tem.org/\">\n"
+ " <Username>aaa</Username>\n"
+ " </GetLeave>\n"
+ " </soap:Body>\n"
+ "</soap:Envelope>";
// 服务器地址
String urlString = "http://xxxxx.asmx";
// 需要调用的方法
String soapActionString = "GetLeaveBalance";
URL url;
try {
url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 拼接soap
String soap = xml;
byte[] buf = soap.getBytes("UTF-8");
// 设置报头
conn.setRequestProperty("Content-Length", String.valueOf(buf.length));
conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
conn.setRequestProperty("soapActionString", soapActionString);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStream out = conn.getOutputStream();
out.write(buf);
out.close();
// 获取响应状态码
int code = conn.getResponseCode();
StringBuffer sb = new StringBuffer();
if (code == HttpStatus.OK.value()) {
InputStream is = conn.getInputStream();
byte[] b = new byte[1024];
int len = 0;
while ((len = is.read(b)) != -1) {
String s = new String(b, 0, len, "utf-8");
sb.append(s);
}
is.close();
}
System.out.println(sb);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
2. 使用HttpClient
public static void test2() throws Exception {
// 输入服务网址
HttpClient client = new HttpClient();
// HttpClient client = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true));
// GetMethod
PostMethod post = new PostMethod("http:/xxxx.asmx/getMethod");
// 设置参数
post.setParameter("username", "aa");
post.setParameter("password", "bddd");
// client.setTimeout(newTimeoutInMilliseconds);
// 执行,返回一个结果码
int code = client.executeMethod(post);
System.out.println("结果码:" + code);
// 获取xml结果
String result = post.getResponseBodyAsString();
System.out.println("结果:" + result);
// 释放连接
post.releaseConnection();
// 关闭连接
((SimpleHttpConnectionManager) client.getHttpConnectionManager()).shutdown();
}
浙公网安备 33010602011771号