SOAP 方式的webservice
话不多说,建议使用SOAP UI工具先行测试你生生成的文件。
soap传输的内容,我用的是最简单的写法,soap这个变量中的格式是用最简单的方式拼接出来的,如果是为了便捷美观,建议使用SOAPBodyElement 。
连接代码如下:
1.HttpClient发送SOAP请求
String wsdl = "连接地址,注意后缀?wsdl,我是去除这个标志的,视情况测试url反馈情况";
int timeout = 100000;
HttpClient client = new HttpClient();
PostMethod postMethod = new PostMethod(wsdl);
// 设置连接超时,其实有没有差别不大
client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);
// 设置读取时间超时,一般接口都有反馈
client.getHttpConnectionManager().getParams().setSoTimeout(timeout);
// 然后把Soap请求数据添加到PostMethod中,注意格式
RequestEntity requestEntity = new StringRequestEntity(soap, "text/xml", "UTF-8");
//设置请求头部,否则可能会报 “no SOAPAction header” 的错误
postMethod.setRequestHeader("SOAPAction","");
// 设置请求体
postMethod.setRequestEntity(requestEntity);
int status = client.executeMethod(postMethod);
// 打印请求状态码
System.out.println("status:" + status);
// 获取响应体输入流
InputStream is = postMethod.getResponseBodyAsStream();
// 获取请求结果字符串
String result = IOUtils.toString(is);
2.HttpURLConnection 发送SOAP请求
URL url = new URL(null,wsdl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(timeout);
conn.setReadTimeout(timeout);
// conn.connect();
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.write(soap.getBytes("utf-8"));
dos.flush();
dos.close();
int code = conn.getResponseCode();
System.out.println(code);
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
String line = null;
StringBuffer strBuf = new StringBuffer();
while ((line = reader.readLine()) != null) {
strBuf.append(line);
}
reader.close();