版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/y_bccl27/article/details/89134583
若一个webservice接口是以.asmx格式来结尾的话,则表明该接口是.net开发的接口
例如:http://www.webxml.com.cn/WebServices/TranslatorWebService.asmx(英文双向翻译服务)
对于.net开发的webservice接口在,Java平台中以常规的第三方jar包来调用会出现错误
使用SoapUI先获取到XML请求报文,然后以最原始的方式(拼接报文)向webService接口地址发送报文调用其服务
package com.demo;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class netWebServiceDemo {
public static void main(String[] args) throws Exception {
callXml("apple");
}
public static void callXml(String word) throws Exception{
//地址
URL url = new URL("http://www.webxml.com.cn/WebServices/TranslatorWebService.asmx");
//调用的方法
String soapActionString = "getEnCnTwoWayTranslator";
//打开链接
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//拼接好xml
StringBuffer sb = new StringBuffer();
sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
sb.append("<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/\">\n"); sb.append("<soap:Body>\n");
sb.append("<getEnCnTwoWayTranslator xmlns=\"http://WebXml.com.cn/\">\n");
sb.append("<Word>");
sb.append(word);
sb.append("</Word>\n");
sb.append("</getEnCnTwoWayTranslator>\n");
sb.append("</soap:Body>\n");
sb.append("</soap:Envelope>\n");
String xmlStr = sb.toString();
System.out.println(xmlStr);
//设置好header信息
con.setRequestMethod("POST");
con.setRequestProperty("content-type", "text/xml; charset=utf-8");
con.setRequestProperty("Content-Length", String.valueOf(xmlStr.getBytes().length));
con.setRequestProperty("soapActionString", soapActionString);
//post请求需要设置
con.setDoOutput(true);
con.setDoInput(true);
//对请求body 往里写xml 设置请求参数
OutputStream ops = con.getOutputStream();
ops.write(xmlStr.getBytes());
ops.flush();
ops.close();
//设置响应回来的信息
InputStream ips = con.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int length = 0;
while( (length = ips.read(buf)) != -1){
baos.write(buf, 0, length);
baos.flush();
}
byte[] responsData = baos.toByteArray();
baos.close();
//处理写响应信息
String responsMess = new String(responsData,"utf-8");
System.out.println(responsMess);
System.out.println(con.getResponseCode());
}
}