springboot1.x调用webservice小记

因工作需要调用webservice接口,不想直接生成类,直接通过相关JAR包调用webservice接口,目前尝试过以下几种方式:

一、axis方式(现在系统在用)

说明:调用JAVA、PHP生成的WEBSERVICE没有问题,但调用.NET开发的WEBSERVICE可能存在问题(我目前遇到的是对方收不到我发送的请求)

maven外用包:

<dependency>
    <groupId>org.apache.axis</groupId>
    <artifactId>axis</artifactId>
    <version>1.4</version>
</dependency>
<dependency>
    <groupId>axis</groupId>
    <artifactId>axis-jaxrpc</artifactId>
    <version>1.4</version>
</dependency>
<dependency>
    <groupId>wsdl4j</groupId>
    <artifactId>wsdl4j</artifactId>
    <version>1.6.2</version>
</dependency>
<dependency>
    <groupId>commons-discovery</groupId>
    <artifactId>commons-discovery</artifactId>
    <version>0.5</version>
</dependency>

如果使用日志包,则要在maven排除

<exclusions>
              <exclusion> 
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
              </exclusion>
              <exclusion> 
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
              </exclusion>
            </exclusions> 

import javax.xml.rpc.ParameterMode;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@org.springframework.stereotype.Service
public class WebService {

    public static void main(String[] args) {
		try {

			String endpoint = "WEBSERVICE_URL";//配置要请求的WEBSERVICE_URL
			Service service = new Service();
			Call call = (Call) service.createCall();
			call.setTargetEndpointAddress(endpoint);
			// WSDL里面描述的接口名称(要调用的方法)
			call.setOperationName("接口方法");

			// call.setEncodingStyle(namespaceURI);
			// 接口方法的参数名, 参数类型,参数模式 IN(输入), OUT(输出) or INOUT(输入输出)
			call.addParameter("参数名", XMLType.XSD_STRING, ParameterMode.IN);
			call.addParameter("参数名", XMLType.XSD_STRING, ParameterMode.IN);
			call.addParameter("参数名", XMLType.XSD_STRING, ParameterMode.IN);
			call.addParameter("参数名", XMLType.XSD_STRING, ParameterMode.IN);
			call.addParameter("参数名", XMLType.XSD_STRING, ParameterMode.IN);
			call.addParameter("参数名", XMLType.XSD_STRING, ParameterMode.IN);

			// 设置被调用方法的返回值类型
			call.setReturnType(XMLType.XSD_SCHEMA);

			// 设置方法中参数的值
			Object[] paramValues = new Object[] { "****","*****", "****",
					"****", "*****", "***" };

			// 解析返回结果
			call.invoke(paramValues);

			String resultXML = call.getResponseMessage().getSOAPPartAsString();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

二、axis2调用方法

此方法在本地IDEA和eclipse测试开发运行正常,但部署后会与springboot1.x中tomcat启动冲突,目前没有找到解决方法。

maven引用:

<dependency>
            <groupId>org.apache.axis2</groupId>
            <artifactId>axis2-adb</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>org.apache.axis2</groupId>
            <artifactId>axis2-kernel</artifactId>
            <version>1.4</version>
        </dependency>

注意:也需要排除日志引用

public Map<String, String> toUser(Map<String, String> map) {

		Map<String, String> resultMap = new HashMap<String, String>();

		try {
			

			Options options = new Options();
			// 指定调用WebService的URL
			EndpointReference targetEPR = new EndpointReference("************");
			options.setTo(targetEPR);
			// options.setAction("urn:getPrice");

			ServiceClient sender = new ServiceClient();
			sender.setOptions(options);

			OMFactory fac = OMAbstractFactory.getOMFactory();
			String tns = "NL";
			// 命名空间,有时命名空间不增加没事,不过最好加上,因为有时有事
			OMNamespace omNs = fac.createOMNamespace(tns, "");

            //调用的接口方法名
			OMElement method = fac.createOMElement("tranfer", omNs);

            //方法对应参数名
			OMElement merchant_id = fac.createOMElement("merchant_id", omNs);
			
			merchant_id.addChild(fac.createOMText(merchant_id, "****"));
			method.addChild(merchant_id);

			method.build();

			OMElement result = sender.sendReceive(method);

			resultMap = XMLUtil.strXmlToMap(result.toString());

			// resultMap.put("resultStatus", statusMap.get("result"));

			resultMap.put("resultXML", result.toString());

			 System.out.println(result);

			// System.out.println(XMLUtil.doXMLParse(result.toString()));

			return resultMap;

		} catch (AxisFault axisFault) {
			axisFault.printStackTrace();

			resultMap.put("response_code", "-99");
			resultMap.put("resultXML", "request error");
		} catch (Exception e) {
			e.printStackTrace();

			resultMap.put("response_code", "-99");
			resultMap.put("resultXML", "request error");
		}

		return resultMap;
	}

三、cxf 调用web service 方式

maven引用:

<dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-core</artifactId>
    <version>3.2.4</version>
</dependency>
<dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-bindings-soap</artifactId>
    <version>3.2.4</version>
</dependency>
<dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-databinding-jaxb</artifactId>
    <version>3.2.4</version>
</dependency>
<dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-frontend-jaxws</artifactId>
    <version>3.2.4</version>
</dependency>
<dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-frontend-simple</artifactId>
    <version>3.2.4</version>
</dependency>
<dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-transports-http</artifactId>
    <version>3.2.4</version>
</dependency>
<dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-transports-udp</artifactId>
    <version>3.2.4</version>
</dependency>
<dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-ws-addr</artifactId>
    <version>3.2.4</version>
</dependency>
<dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-wsdl</artifactId>
    <version>3.2.4</version>
</dependency>
<dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-ws-policy</artifactId>
    <version>3.2.4</version>
</dependency>
<dependency>
    <groupId>org.apache.neethi</groupId>
    <artifactId>neethi</artifactId>
    <version>3.1.1</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.25</version>
</dependency>
<dependency>
    <groupId>org.apache.ws.xmlschema</groupId>
    <artifactId>xmlschema-core</artifactId>
    <version>2.2.1</version>
</dependency>
<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.0</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.core</groupId>
    <artifactId>jersey-client</artifactId>
    <version>2.27</version>
</dependency>

JAVA代码:主要是返回值没有找到相关方法全部获取

public static void main(String[] args) {
		// 创建动态客户端
		JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
		Client client = dcf.createClient("https://********?wsdl");
		// 需要密码的情况需要加上用户名和密码
		// client.getOutInterceptors().add(new ClientLoginInterceptor(USER_NAME,
		// PASS_WORD));
		Object[] objects = new Object[0];
		try {
			// invoke("方法名",参数1,参数2,参数3....);
			objects = client.invoke("getInfo", "Leftso");
			System.out.println("返回数据:" + objects[0]);
		} catch (java.lang.Exception e) {
			e.printStackTrace();
		}
	}

四、xfire 调用web service

打包后,执行前需要将spring 1.X.jar删除

参考:https://www.2cto.com/kf/201606/515737.html

五、http 调用方式(使用此种方法调用.NET开发的服务)


package test2;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;


public class HttpWebserviceTest {
	public static void main(String[] args) {
		InputStreamReader bis = null;

		OutputStreamWriter printWriter = null;

		String body = "";

		try {

            //解决HTTPS请求
			HttpURLConnection httpURLConnection = SSLTrustManager
					.connect("https://*************.asmx?op=方法名");

			httpURLConnection.setRequestMethod("POST");// 提交模式

			httpURLConnection.setDoOutput(true);

			httpURLConnection.setDoInput(true);

			httpURLConnection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
            //解决403
			httpURLConnection.setRequestProperty("User-Agent",
					"Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
			httpURLConnection.setRequestProperty("User-Agent",
					"Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

			// 获取URLConnection对象对应的输出流

			printWriter = new OutputStreamWriter(httpURLConnection.getOutputStream(), "UTF-8");

			// 发送请求参数
			StringBuilder soap = new StringBuilder(); // 构造请求报文

			soap.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/\">");
			soap.append("  <soap:Body>");
			soap.append("    <RequestPayoutEx xmlns=\"http://******/\">");
			soap.append("     <apiKey>****</apiKey>");
			soap.append(" </RequestPayoutEx>");
			soap.append(" </soap:Body>");
			soap.append("</soap:Envelope>");

			printWriter.write(soap.toString());
			// flush输出流的缓冲

			printWriter.flush();

			// 开始获取数据

			bis = new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8");

			int len;

			char[] arr = new char[1024];

			while ((len = bis.read(arr)) != -1) {

				body += new String(arr, 0, len);

			}
			System.out.println(body);

		} catch (Exception e) {

			e.printStackTrace();

		} finally {

			if (bis != null) {

				try {

					bis.close();

				} catch (IOException e) {

					e.printStackTrace();

				}

			}

			if (printWriter != null) {

				try {

					printWriter.close();

				} catch (IOException e) {

					e.printStackTrace();

				}

			}

		}

	}
}

package test2;

import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;

public class SSLTrustManager implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager, HostnameVerifier {
	public java.security.cert.X509Certificate[] getAcceptedIssuers() {
		return null;
	}

	public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {
		return true;
	}

	public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {
		return true;
	}

	public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
			throws java.security.cert.CertificateException {
		return;
	}

	public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
			throws java.security.cert.CertificateException {
		return;
	}

	public boolean verify(String urlHostName, SSLSession session) { // 允许所有主机
		return true;
	}

	public static HttpURLConnection connect(String strUrl) throws Exception {

		javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
		javax.net.ssl.TrustManager tm = new SSLTrustManager();
		trustAllCerts[0] = tm;
		javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
		sc.init(null, trustAllCerts, null);
		javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

		HttpsURLConnection.setDefaultHostnameVerifier((HostnameVerifier) tm);

		URL url = new URL(strUrl);
		HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
		urlConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

		return urlConn;
	}

}

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值