各类接口调用方式

一、Webservice

(1)axis

package com.micromis.common.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import javax.xml.rpc.ServiceException;
import javax.xml.rpc.encoding.XMLType;

import org.apache.axis.client.Call;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;
import com.micromis.common.cache.OutsideCache;
import com.micromis.common.constants.SysConst;
import com.micromis.common.framework.BusinessException;
import com.micromis.fxmis.entity.cond.CallServiceCond;
import com.micromis.fxmis.entity.cond.FtpUploadCond;
import com.micromis.fxmis.entity.generator.DisFileRecord;
import com.micromis.fxmis.entity.generator.DisOutsideFtp;
import com.micromis.fxmis.entity.generator.DisOutsideService;
import com.micromis.fxmis.mapper.generator.mapper.DisFileRecordMapper;

/**
 * 

接口服务工具类

* @author */ @Service public class ServiceUtil { private static final Logger logger = LoggerFactory.getLogger(ServiceUtil.class); @Autowired private DisFileRecordMapper disFileRecordMapper; @Autowired private OutsideCache outsideCache; /** *

远程服务调用类

* @param cond * @return * @throws BusinessException * @author */ public String callService( CallServiceCond cond ) throws BusinessException { String responseStr = null;//返回报文(String类型) String serviceId = cond.getServiceId(); DisOutsideService outsideService = outsideCache.getDisOutsideService( serviceId );//接口信息配置信息 try { if(outsideService != null){ String serviceName = outsideService.getServiceName(); //服务名称 logger.info("{}系统服务调用开始...", serviceName); String serviceType = outsideService.getServiceType(); //服务类型 if(SysConst.WEBSERVICE.equals( serviceType )) { String content = cond.getContent(); String charset = cond.getCharset(); responseStr = this.call( outsideService, content, charset ); } else if ( SysConst.SFTP.equals( serviceType ) ){ // 生成文件 responseStr = uploadFile( cond ); } logger.info("{}系统服务调用结束...", serviceName); } else { throw new BusinessException(serviceId+"外围系统服务配置信息不存在!", "01"); } } catch ( BusinessException e ) { e.printStackTrace(); throw e; } return responseStr; } /** *

文件上传到ftp/sftp服务器 * - 可支持上传多个文件、上传单个压缩文件、预清空远程目录下的文件和上传临时文件

* @param cond * @return * @throws BusinessException * @author */ public String uploadFile( CallServiceCond cond ) throws BusinessException { String result = null; String serviceId = cond.getServiceId(); DisOutsideService outsideService = outsideCache.getDisOutsideService( serviceId );//接口信息配置信息 String ftpType = outsideService.getFtpType(); // ftp类型 DisOutsideFtp outsideFtp = outsideCache.getDisOutsideFtp( ftpType ); // ftp服务配置信息 // 准备连接sftp的参数(含路径拼接) String ip = outsideFtp.getIp(); int port = outsideFtp.getPort(); String userName = outsideFtp.getUsername(); String password = outsideFtp.getPassword(); String newFtpPath = ""; if( "0".equals( cond.getCallType() ) ) newFtpPath = outsideFtp.getFtpPath(); else newFtpPath = outsideFtp.getFtpManualPath(); String newLocalPath = outsideFtp.getLocalPath(); Date pathDate = cond.getPathDate(); if(pathDate != null){ String localPath = outsideFtp.getLocalPath(); String year = DateUtil.getYear(pathDate); String month = DateUtil.getMonth(pathDate); String day = DateUtil.getDay(pathDate); newFtpPath += "/" + year + "/" + month + "/" + day; //拼接后的路径 newLocalPath = localPath + "/" + year + "/" + month + "/" + day; } // 判断是否需要先清空远程目录下的文件 Boolean preClearDir = cond.getPreClearDir(); if( preClearDir != null && preClearDir == true ) { try { SftpUtils.clearDirFile(ip, port, userName, password, newFtpPath); } catch (JSchException e) { e.printStackTrace(); logger.info("【{}】预清除文件时异常!", outsideService.getServiceName(), e); throw new BusinessException("服务"+outsideService.getServiceName()+"上传文件异常", "02"); } catch (SftpException e) { e.printStackTrace(); logger.info("【{}】上传文件异常!", outsideService.getServiceName(), e); throw new BusinessException(outsideService.getServiceName()+"上传文件异常", "02"); } } // 上传文件 List fileList = cond.getFileList(); //待上传文件列表 String zipFileName = cond.getZipFileName(); //压缩文件名 Boolean zipFlag = cond.getZipFlag(); if( fileList != null && fileList.size() > 0 ) { //判断是否要压缩 if( zipFlag != null && zipFlag == true ) { if( zipFileName == null || "".equals(zipFileName) ){ zipFileName = fileList.get(0).getFileName().replaceAll("[\\.][^.]+$", "") + ".zip"; } //压缩到本地 List srcFiles = new ArrayList(); //待压缩的文件 //1.先将文件保存在本地 for(FtpUploadCond file : fileList) { String fileName = file.getFileName(); String content = file.getContent(); FileUtil.saveLocalFile(newLocalPath, fileName, content); File srcFile = new File( newLocalPath + "/" + fileName ); srcFiles.add(srcFile); } //2.进行压缩 File destFile = new File(newLocalPath + "/" + zipFileName); //压缩后的文件名 ZipUtils.compress(srcFiles, destFile); //上传压缩文件 try { InputStream inputStream = new FileInputStream( destFile ); SftpUtils.upload(ip, port, userName, password, newFtpPath, zipFileName, inputStream); } catch (FileNotFoundException e) { result = "fail"; e.printStackTrace(); logger.info("【{}】上传文件异常,未找到待上传的压缩文件!", outsideService.getServiceName(), e); throw new BusinessException(outsideService.getServiceName()+"上传文件异常,未找到待上传的压缩文件", "02"); } catch (JSchException e) { result = "fail"; e.printStackTrace(); logger.info("【{}】上传文件异常!", outsideService.getServiceName(), e); throw new BusinessException("服务"+outsideService.getServiceName()+"上传文件异常", "02"); } catch (SftpException e) { result = "fail"; e.printStackTrace(); logger.info("【{}】服务上传文件异常!", outsideService.getServiceName(), e); throw new BusinessException("服务"+outsideService.getServiceName()+"上传文件异常", "02"); } result = "succ"; } else { //不压缩直接上传 for(FtpUploadCond file : fileList) { String fileName = file.getFileName(); String content = file.getContent(); try { boolean flag = SftpUtils.upload(ip, port, userName, password, newFtpPath, fileName, content); if(!flag) result = "fail"; } catch (JSchException e) { result = "fail"; e.printStackTrace(); logger.info("【{}】上传文件异常!", outsideService.getServiceName(), e); throw new BusinessException("服务"+outsideService.getServiceName()+"上传文件异常", "02"); } catch (SftpException e) { result = "fail"; e.printStackTrace(); logger.info("【{}】上传文件异常!", outsideService.getServiceName(), e); throw new BusinessException(outsideService.getServiceName()+"上传文件异常", "02"); } result = "succ"; } } } // 判断是否要上传临时文件 if("succ".equals(result)) { String tempFileName = cond.getTempFileName(); if(tempFileName != null && !tempFileName.equals("")) { try { String tempFilePath = cond.getTempFilePath(); if( tempFilePath == null ) tempFilePath = newFtpPath; boolean flag = SftpUtils.upload(ip, port, userName, password, tempFilePath, tempFileName, cond.getTempFileContent()); if(!flag) result = "fail"; } catch (JSchException e) { result = "fail"; e.printStackTrace(); logger.info("【{}】上传临时文件异常!", outsideService.getServiceName(), e); throw new BusinessException("服务"+outsideService.getServiceName()+"上传临时文件异常", "02"); } catch (SftpException e) { result = "fail"; e.printStackTrace(); logger.info("【{}】上传临时文件异常!", outsideService.getServiceName(), e); throw new BusinessException("服务"+outsideService.getServiceName()+"上传临时文件异常", "02"); } } } // 数据库添加记录 if("succ".equals(result)) { for(FtpUploadCond file : fileList) { // 在数据库添加文件上传的记录 DisFileRecord disFileRecord = new DisFileRecord(); disFileRecord.setServiceId( outsideService.getServiceId() ); disFileRecord.setOptType("0"); disFileRecord.setFileType( outsideService.getFtpType() ); disFileRecord.setFileName(file.getFileName()); disFileRecord.setState( result ); disFileRecord.setDesc( outsideService.getServiceName() + "的文件上传" ); disFileRecord.setOptDate( new Date() ); disFileRecord.setRemotePath( outsideFtp.getFtpPath() ); disFileRecord.setLocalPath( outsideFtp.getLocalPath() ); disFileRecord.setCreatedUser("sys"); disFileRecord.setCreatedDate( new Date() ); disFileRecordMapper.insertSelective(disFileRecord); } if( zipFlag != null && zipFlag == true ) { DisFileRecord disFileRecord = new DisFileRecord(); disFileRecord.setServiceId( outsideService.getServiceId() ); disFileRecord.setOptType("0"); disFileRecord.setFileType( outsideService.getFtpType() ); disFileRecord.setFileName( zipFileName ); disFileRecord.setState( result ); disFileRecord.setDesc( outsideService.getServiceName() + "的文件上传" ); disFileRecord.setOptDate( new Date() ); disFileRecord.setRemotePath( outsideFtp.getFtpPath() ); disFileRecord.setLocalPath( outsideFtp.getLocalPath() ); disFileRecord.setCreatedUser("sys"); disFileRecord.setCreatedDate( new Date() ); disFileRecordMapper.insertSelective(disFileRecord); } } // 本地备份 if("succ".equals(result)) { if( zipFlag == null || zipFlag == false ) { for(FtpUploadCond file : fileList) { String fileName = file.getFileName(); String content = file.getContent(); FileUtil.saveLocalFile(newLocalPath, fileName, content); } } } return result; } /** *

远程服务调用类

* @param serviceId * @param content 请求或上传内容 * @param fileName 上传文件名 * @param pathDate 用于拼接ftpPath 可为空 * @return * @throws BusinessException * @author */ public String callService( String serviceId, String content, String fileName, Date pathDate ) throws BusinessException { String responseStr = null;//返回报文(String类型) DisOutsideService outsideService =outsideCache.getDisOutsideService(serviceId);//接口信息配置信息 String serviceName = null; // 如果接口配置信息不为空 if(outsideService != null){ try { serviceName = outsideService.getServiceName(); //服务名称 logger.info("{}系统服务调用开始...", serviceName); String serviceType = outsideService.getServiceType(); //服务类型 if( SysConst.WEBSERVICE.equals( serviceType ) ){ // 调webservice接口 responseStr = this.call( outsideService, content, null ); } else if ( SysConst.SFTP.equals( serviceType ) ){ // 生成文件 responseStr = uploadFile( outsideService, fileName, content, pathDate ); } logger.info("{}系统服务调用结束...", serviceName); } catch ( BusinessException e ) { e.printStackTrace(); throw e; } } else { logger.info("外围系统服务配置信息不存在!"); throw new BusinessException(serviceId+"外围系统服务配置信息不存在!", "01"); } return responseStr; } /** *

文件上传SFTP

* @param outsideService * @param fileName * @param content 上传内容 * @param pathDate 用于拼接ftpPath 可为空 * @return * @author * @throws SftpException * @throws JSchException */ private String uploadFile( DisOutsideService outsideService, String fileName, String content, Date pathDate ) throws BusinessException { String result = null; String ftpType = outsideService.getFtpType(); // ftp类型 DisOutsideFtp outsideFtp = outsideCache.getDisOutsideFtp( ftpType ); // ftp服务配置信息 boolean flag = false; try { // 准备连接sftp的参数(含路径拼接) String ip = outsideFtp.getIp(); int port = outsideFtp.getPort(); String userName = outsideFtp.getUsername(); String password = outsideFtp.getPassword(); String newFtpPath = outsideFtp.getFtpPath(); String newLocalPath = outsideFtp.getLocalPath(); if(pathDate != null){ String ftpPath = outsideFtp.getFtpPath(); String localPath = outsideFtp.getLocalPath(); String year = DateUtil.getYear(pathDate); String month = DateUtil.getMonth(pathDate); String day = DateUtil.getDay(pathDate); newFtpPath = ftpPath + "/" + year + "/" + month + "/" + day; //拼接后的路径 newLocalPath = localPath + "/" + year + "/" + month + "/" + day; } flag = SftpUtils.upload(ip, port, userName, password, newFtpPath, fileName, content); if( flag ) { logger.info("文件上传成功!"); result = "succ"; // 将文件在本地备份 FileUtil.saveLocalFile(newLocalPath, fileName, content); } else { logger.info("文件上传失败!"); result = "fail"; } } catch ( JSchException e ) { result = "fail"; e.printStackTrace(); logger.info("【{}】上传文件异常!", outsideService.getServiceName(), e); throw new BusinessException("服务"+outsideService.getServiceName()+"上传文件异常", "02"); } catch ( SftpException e ) { result = "fail"; e.printStackTrace(); logger.info("【{}】上传文件异常!", outsideService.getServiceName(), e); throw new BusinessException(outsideService.getServiceName()+"上传文件异常", "02"); } finally { // 在数据库添加文件上传的记录 DisFileRecord disFileRecord = new DisFileRecord(); disFileRecord.setServiceId( outsideService.getServiceId() ); disFileRecord.setOptType("0"); disFileRecord.setFileType( outsideService.getFtpType() ); disFileRecord.setFileName(fileName); disFileRecord.setState( flag ? "succ" : "fail" ); disFileRecord.setDesc( outsideService.getServiceName() + "的文件上传" ); disFileRecord.setOptDate( new Date() ); disFileRecord.setRemotePath( outsideFtp.getFtpPath() ); disFileRecord.setLocalPath( outsideFtp.getLocalPath() ); disFileRecord.setCreatedUser("sys"); disFileRecord.setCreatedDate( new Date() ); disFileRecordMapper.insertSelective(disFileRecord); } return result; } /** *

调用webservice接口

* @param outsideService * @param requestStr 请求内容 * @return * @author * @throws ServiceException * @throws RemoteException */ public String call( DisOutsideService outsideService, String requestStr, String charset ) throws BusinessException { String result=null; org.apache.axis.client.Service service = new org.apache.axis.client.Service(); String serviceUrl = outsideService.getServiceUrl();//服务地址url logger.info(serviceUrl); String serviceMethod = outsideService.getServiceMethod();//服务方法 Call call = null; try { call = (Call) service.createCall(); call.setTargetEndpointAddress(new URL(serviceUrl)); call.setOperationName(new QName(serviceMethod)); if( outsideService.getTimeOut() != null ) { call.setTimeout(outsideService.getTimeOut());//设置超时时间 } else { call.setTimeout(5000);//设置超时时间,单位毫秒 } if( charset != null && !"".equals(charset) ){ call.setEncodingStyle(charset); } // call.setUseSOAPAction(true); call.addParameter("requestXmlData", XMLType.XSD_STRING, ParameterMode.IN); call.setReturnType(XMLType.XSD_STRING); Date startTime = new Date(); logger.info("请求【{}】服务时间:[{}]", outsideService.getServiceName(), DateUtil.formatDate2Str(startTime, DateUtil.DATE_TIME_PATTON_1)); logger.info("调用【{}】请求报文:[{}]", outsideService.getServiceName(), requestStr); result = (String) call.invoke(new Object[] { requestStr }); Date endTime = new Date(); logger.info("服务【{}】返回时间:[{}]", outsideService.getServiceName(), DateUtil.formatDate2Str(endTime, DateUtil.DATE_TIME_PATTON_1)); logger.info("调用【{}】耗时:[{}]", outsideService.getServiceName(), DateUtil.caculSecondDiffer(startTime, endTime) ); logger.info("调用【{}】返回报文:[{}]", outsideService.getServiceName(), result); }catch (MalformedURLException e) { e.printStackTrace(); logger.info("请求【{}】服务异常", outsideService.getServiceName(), e); throw new BusinessException("请求"+outsideService.getServiceName()+"服务异常,可能是远程URL不正确或异常", "01"); }catch (ServiceException e) { logger.info("请求【{}】服务异常", outsideService.getServiceName(), e); e.printStackTrace(); throw new BusinessException("请求"+outsideService.getServiceName()+"服务异常,可能是远程服务出现异常", "01"); } catch (RemoteException e) { logger.info("请求【{}】服务异常", outsideService.getServiceName(), e); e.printStackTrace(); throw new BusinessException("请求"+outsideService.getServiceName()+"服务异常,可能是网络超时了。。", "01"); } return result; } }




(2)axis2

package com.micromis.fxmis.service.allianz;


import java.io.UnsupportedEncodingException;

import javax.xml.namespace.QName;

import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.rpc.client.RPCServiceClient;

public class AllianzWebServiceUtil {

	private final static String WEBSERVICE_URL = "http://10.253.111.111:8080/dscc/services/TransMobileService?wsdl";
	private final static String WEBSERVICE_SOAPSPACE = "http://webservice.modules.jeesite.thinkgem.com";
	private final static String WEBSERVICE_METHOD = "exchange";

	public static String doWebService(String url, String soapspace, String method, String xml,String tFlag){
		try{
			RPCServiceClient client = new RPCServiceClient();
			Options options = client.getOptions();

			EndpointReference er = new EndpointReference(url);
			options.setTo(er);
			
			QName qName = new QName(soapspace,method);
//			QName qName = new QName(method);
			
			Object[] param = new Object[] { xml,tFlag };
			Class[] classes = new Class[]{String.class};
			
			String result = (String) client.invokeBlocking(qName, param, classes)[0];
			
			return result;
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	} 
	
	public static void main(String[] args) throws UnsupportedEncodingException {
		//如加密直接发送密文
		String str = new String(""+
				""+
				  ""+
				    "AC00003900021456305194844"+
				    "0003"+
				    "1"+
				    "0000"+
				    "结果"+
				  ""+
				  ""+
				    "301-1-593-16-0000017390-00"+
				    "70"+
				  ""+
				"");
		//格式为"配置渠道代码编码/配置接口编码"
		String tFlag = "ehb/insure";
		String res = AllianzWebServiceUtil.doWebService(WEBSERVICE_URL, WEBSERVICE_SOAPSPACE, WEBSERVICE_METHOD, str, tFlag);
		System.out.println("结果" + res);
	}
	
}


二、HttpClient

package com.micromis.common.utils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.micromis.common.constants.SysConst;

/**
 * 

Http工具类

* @author yunrong.lai001 */ public class HttpUtil { /** *

发送get请求

* @param url url自行拼接参数 * @return * @throws ParseException * @throws IOException * @author yunrong.lai001 */ public static String get( String url ) throws ParseException, IOException { String result = null; CloseableHttpClient httpclient = HttpClients.createDefault(); RequestConfig requestConfig = RequestConfig.custom() .setConnectionRequestTimeout(SysConst.CONNECT_TIMEOUT) .setConnectTimeout(SysConst.CONNECT_TIMEOUT) .setSocketTimeout(SysConst.SO_TIMEOUT) .build(); try { HttpGet httpGet = new HttpGet( url ); // httpGet.addHeader("Content-type" , "text/html; charset=utf-8"); httpGet.setConfig(requestConfig); CloseableHttpResponse response = httpclient.execute( httpGet ); HttpEntity entity = response.getEntity(); if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK && entity != null ){ result = EntityUtils.toString( entity, SysConst.UTF_8 ); } response.close(); } catch (ClientProtocolException e) { e.printStackTrace(); } finally { try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } return result; } /** *

发送post请求

* @param url * @param paramMap 参数集合 * @return * @throws ParseException * @throws IOException * @author */ public static String post( String url, Map paramMap ) throws ParseException, IOException { String result = null; CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost( url ); RequestConfig requestConfig = RequestConfig.custom() .setConnectionRequestTimeout(SysConst.CONNECT_TIMEOUT) .setConnectTimeout(SysConst.CONNECT_TIMEOUT) .setSocketTimeout(SysConst.SO_TIMEOUT) .build(); List nameValuePair = new ArrayList(); if( paramMap != null && paramMap.size() > 0 ) { for( Map.Entry entry : paramMap.entrySet() ) { String key = entry.getKey().toString(); String value = entry.getValue().toString(); nameValuePair.add( new BasicNameValuePair( key, value ) ); } } UrlEncodedFormEntity uefEntity; try { httppost.addHeader("Content-type", "application/x-www-form-urlencoded;charset=UTF-8"); uefEntity = new UrlEncodedFormEntity( nameValuePair, SysConst.UTF_8 ); httppost.setEntity( uefEntity ); httppost.setConfig(requestConfig); CloseableHttpResponse response = httpclient.execute( httppost ); HttpEntity entity = response.getEntity(); if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK && entity != null ){ result = EntityUtils.toString( entity ); } response.close(); } catch (ClientProtocolException e) { e.printStackTrace(); } finally { try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } return result; } public static String postXml( String url, String requestStr ) throws ParseException, IOException { String result = post( url, requestStr, "text/xml", SysConst.UTF_8 ); return result; } public static String postJson( String url, String requestStr ) throws ParseException, IOException { String result = post( url, requestStr, "application/json", SysConst.UTF_8 ); return result; } /** *

发送post请求

* @param url * @param requestStr 请求报文体 * @param contentType 请求报文体类型 * @param charset * @return * @throws ParseException * @throws IOException * @author */ public static String post( String url, String requestStr, String contentType, String charset ) throws ParseException, IOException { String result = null; CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost( url ); RequestConfig requestConfig = RequestConfig.custom() .setConnectionRequestTimeout(SysConst.CONNECT_TIMEOUT) .setConnectTimeout(SysConst.CONNECT_TIMEOUT) .setSocketTimeout(SysConst.SO_TIMEOUT) .build(); try { httppost.addHeader("Content-Type", contentType ); httppost.addHeader("charset", charset ); StringEntity strEntity = new StringEntity( requestStr, Charset.forName(charset) ); httppost.setEntity( strEntity ); httppost.setConfig(requestConfig); //执行post请求 CloseableHttpResponse response = httpclient.execute( httppost ); //获得返回的http响应对象 HttpEntity entity = response.getEntity(); if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK && entity != null ){ result = EntityUtils.toString( entity, charset ); } response.close(); } catch (ClientProtocolException e) { e.printStackTrace(); } finally { try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } return result; } }


你可能感兴趣的:(各类接口调用方式)