动态调用第三方rest soap

    <!-- hutool 调用第三方 -->
    <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-all</artifactId>
        <version>4.1.0</version>
    </dependency>
package com.xgit.iot.infra.third;

import java.util.HashMap;
import java.util.Map;

import org.apache.logging.log4j.util.Strings;

import cn.hutool.http.HttpUtil;

public class HutoolUtil {
 
    /**
     * get方法(无需header)
     * @param url 请求参数
     * @param paramMap 入参
     * @return
     * @throws Exception 
     */
    public static String hutoolGetNoHeader(String url, Map<String, Object> paramMap) throws Exception {
        String result = Strings.EMPTY;
        try {
            if (null == paramMap || paramMap.isEmpty()) {
                result = HttpUtil.get(url);
             }else {
                 result =  HttpUtil.get(url, paramMap);
             }
        }catch (Exception e){
            throw new Exception("第三方接口异常", e);
        }
        return result;
    }
    
    
    public static String hutoolPostNoHeader(String url, Map<String, Object> paramMap) throws Exception{
        String result = Strings.EMPTY;
        try{
            result = HttpUtil.post(url, paramMap);
        }catch (Exception e){
            throw new Exception("第三方接口异常", e);
        }
        return result;
        
    }
    
    public static String hutoolGet(String url, Map<String, Object> paramMap) {
        String getResult = HttpUtil
                .createGet(url)
                .header("Content-Type","application/json")
                .form(paramMap)
                .execute()
                .charset("UTF-8")
                .body();
        return getResult;
    }
    
    public static String hutoolPost(String url, Map<String, Object> paramMap) {

        JSONObject jsonObject = new JSONObject(paramMap);

        String postResult = HttpUtil
                .createPost(url)
                .contentType("application/json")
//                .header("Content-Type", "application/json")
//                .header("token", token)
                .body(jsonObject)
                .timeout(HttpRequest.TIMEOUT_DEFAULT)
                .execute()
                .body();

//        JSONObject jsonObject = JSONUtil.createObj();
//        jsonObject.put("account", "hangyun@xris.com");
//        jsonObject.put("passwd", "xris@#swkd5");
//        jsonObject.put("timeStamp", "1616463501721");
        return postResult;
    }
}

附带解析样例

public static List<String> parseApiResult(String result) {
        log.info("api result: " + result);
        if (StringUtils.isBlank(result)) {
            return null;
        }
        JSONObject jsonResult = JSON.parseObject(result);
        String data = jsonResult.getString("code");
        if (StringUtils.isBlank(data) || !"200".equals(data)) {
            return null;
        }
        Object value = jsonResult.get("value");
        if (null == value) {
            return null;
        }
        List<String> menuList = Lists.newArrayList();
        if (value instanceof JSONArray) {
            JSONArray jsonArray = jsonResult.getJSONArray("value");
            for(int i=0; i<jsonArray.size(); i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                Iterator iter = jsonObject.entrySet().iterator();
                while(iter.hasNext()){
                    Map.Entry entry = (Map.Entry) iter.next();
                    //entry.getValue().toString()
                    menuList.add(entry.getKey().toString());
                }
            }
        }else {
            Map maps = (Map) JSON.parse(value.toString());
            for (Object map : maps.entrySet()) {
                //(Map.Entry) map).getValue()  stream循环也行
                menuList.add(((Map.Entry) map).getKey().toString());
            }
        }
        return menuList;
    }

内部跨服务调用,可写入api,打成架包,直接引用
ResultInfo resultInfo = PlatformHelper.checkToken(token);



/**
 * 注释:
 *
 * @author hz
 * @version 1.0.0
 * @createTime: 2019/11/8 11:34
 * @since 1.0
 */
@EnableFeignClients
@FeignClient("iot-server")
public interface mailServerClient {
    /**
     *
     * @param sendMailVO
     * @return
     */
    @RequestMapping(value = "/SysMail/sendMail", method = RequestMethod.POST)
    ActionResult<Boolean> sendMail(@RequestBody SendMailVO sendMailVO);

}

xfire调用soap

<dependency>
	<groupId>org.codehaus.xfire</groupId>
	<artifactId>xfire-aegis</artifactId>
	<version>1.2.6</version>
</dependency>
<dependency>
	<groupId>org.codehaus.xfire</groupId>
	<artifactId>xfire-core</artifactId>
	<version>1.2.6</version>
</dependency>
package com.xgit.iot.infra.third;

import java.net.MalformedURLException;
import java.net.URL;

import org.codehaus.xfire.client.Client;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XfireSoapUtil {

    public static void main(String[] args) throws MalformedURLException, Exception {

        // http://test.third.common.work.xgit.com 明明空间纯路径 不以 / 结尾
        String url = "http://localhost:9007/services/user?wsdl";
        String method = "getUser";
        
        try {
            Client client = new Client(new URL(url));
            Object[] res = client.invoke(method, new String[] {"1"});
            
            //遍历返回的 List<Object> 集合对象
            for(int i=0;i<res.length;i++){
                Element element = ((Document)res[i]).getDocumentElement();
                //child节点存数据     attri节点存命名空间等
                NodeList children = element.getChildNodes(); 
                for (int j = 0; j < children.getLength(); j++) { 
                   Node node = children.item(j);
                   // 解析每个节点 数组会自动拆分为单节点 如3个节点 有个数组,长度2,变为4个节点
                   stepThrough(node);
                } 
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
    
    private static void stepThrough(Node node) {
       // 解析每个节点 数组会自动拆分为单节点 如3个节点 有个数组,长度2,变为4个节点
        for (Node child = node.getFirstChild(); child!= null; child = child.getNextSibling()) { 
            NodeList childList = child.getChildNodes(); 
            if(child instanceof Node && (1 == childList.getLength()))
            {   // 每个节点一个字段 数组内对象只塞一个字段 走这里
                // child.getNodeName()为字段名
                System.out.println(child.getNodeName() + "|" + child.getTextContent());
            }else {
                // 每个节点多个字段 数组内对象塞多个字段字段 走这里
                stepThrough(child);
            } 
         }
    }

}

cxf调用soap接口以及样例 ==默认是用cxf

 <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-spring-boot-starter-jaxws</artifactId>
        <version>3.2.4</version>
	</dependency>


 public static void main(String url, String method, String param) {
         JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();

        // 创建动态客户端
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        // 需要密码的情况需要加上用户名和密码
        // client.getOutInterceptors().add(new ClientLoginInterceptor(USER_NAME,
        // PASS_WORD));
        Client client = dcf.createClient(url);

        try {
            
            Object[] res = client.invoke(method, new String[] {"1"});
            // 一个方法中多次调用 需要重置上下文   ==大坑啊
            Thread.currentThread().setContextClassLoader(cl);

            String result = Strings.EMPTY;
            if (res[0] instanceof String) {
                result = String.valueOf(res[0]);
            } else {
                result = JSON.toJSONString(res[0]);
            }
            System.out.println(result);
            JSONObject jsonResult = JSON.parseObject(result);
            String userId = jsonResult.getString("staCode");
            System.out.println(userId);
            

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

springboot soap样例

写法一 命名空间必须带 / 否则cxf无法使用 xfire 不能带/ cxf是xfire升級版

package com.xgit.work.common.third.test;

import java.io.UnsupportedEncodingException;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;

@WebService  //写法一 不加命名空间  但是接口命名空间后要加 / 否则 cxf无法使用 
public interface AppService {
    @WebMethod
    @WebResult(name = "out", targetNamespace = "http://test.third.common.work.xgit.com/")
    String getUserName(@WebParam(name = "id") String id) throws UnsupportedEncodingException;
    @WebMethod
    public User getUser(String id) throws UnsupportedEncodingException;
}
package com.xgit.work.common.third.test;


import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.jws.WebService;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;

//name暴露的服务名称, targetNamespace:命名空间,设置为接口的包名倒写(默认是本类包名倒写). endpointInterface接口地址
@WebService(name = "test" ,targetNamespace ="http://test.third.common.work.xgit.com/" ,endpointInterface = "com.xgit.work.common.third.test.AppService")
public class AppServiceImpl implements AppService {
  @Override
  public String getUserName(String id) throws UnsupportedEncodingException {
      System.out.println("==========================="+id);
      User result= new User();
      result.setStaCode("1");
      result.setMsg("调用成功");
      UserInfo retContent = new UserInfo();
      retContent.setFid("fdsf131e");
      retContent.setFnumber("12345");
      retContent.setFname("zxy");
//      result.setRetContent(retContent);
      return JSON.toJSONString(result);
  }
  @Override
  public User getUser(String id)throws UnsupportedEncodingException  {
      System.out.println("==========================="+id);
      User result= new User();
      result.setStaCode("1");
      result.setMsg("调用成功");
      UserInfo retContent = new UserInfo();
      retContent.setFid("contentid1");
      retContent.setFnumber("number1");
      retContent.setFname("name1");
      
      UserInfo retContent3 = new UserInfo();
      retContent3.setFid("contentid2");
      retContent3.setFnumber("number2");
      retContent3.setFname("name2");
      List<UserInfo> aa =Lists.newArrayList();
      aa.add(retContent);
      aa.add(retContent3);
      result.setRetContent(aa);
//      UserInfo[] bb = {retContent, retContent3};
//      result.setRetContent2(bb);
      return result;
  }

}

写法2 统一命名空间


@WebService(targetNamespace = "http://service.demo.third.infra.iot.xgit.com")
public interface UserService {

	@WebMethod//标注该方法为webservice暴露的方法,用于向外公布,它修饰的方法是webservice方法,去掉也没影响的,类似一个注释信息。
	public User getUser(@WebParam(name = "userId") String userId);
	
	@WebMethod//(exclude=true)该犯法不暴露,静态方法和final方法不暴露
	public String getUserName(@WebParam(name = "userId") String userId);
	
}

@WebService(serviceName="UserService",//对外发布的服务名
			targetNamespace="http://service.demo.third.infra.iot.xgit.com",//指定你想要的名称空间,通常使用使用包名反转
			endpointInterface="com.xgit.iot.infra.third.demo.service.UserService")//服务接口全路径, 指定做SEI(Service EndPoint Interface)服务端点接口
@Component
public class UserServiceImpl implements UserService{

	private Map<String, User> userMap = new HashMap<String, User>();
	public UserServiceImpl() {
	    System.out.println("向实体类插入数据");
	    User user = new User();
	    user.setUserId("123");
		user.setUserName("test1");
		user.setEmail("maplefix@163.xom");
	    userMap.put(user.getUserId(), user);
	    
	    user = new User();
	    user.setUserId(UUID.randomUUID().toString().replace("-", ""));
		user.setUserName("test2");
		user.setEmail("maplefix@163.xom");
	    userMap.put(user.getUserId(), user);
	    
	    user = new User();
	    user.setUserId(UUID.randomUUID().toString().replace("-", ""));
		user.setUserName("test3");
		user.setEmail("maplefix@163.xom");
	    userMap.put(user.getUserId(), user);
	}
	@Override
	public String getUserName(String userId) {
	    return "test" + userId;
	}
	@Override
	public User getUser(String userId) {
	    System.out.println("userMap是:"+userMap);
	    return userMap.get(userId);
	}
package com.xgit.work.common.third.test;


import java.io.Serializable;
import java.util.List;

import lombok.Data;
/**
 * @ClassName:User
 * @Description:测试实体
 * @author Jerry
 * @date:2018年4月10日下午3:57:38
 */
@Data
public class User implements Serializable{

    private static final long serialVersionUID = -3628469724795296287L;

    private String staCode;
    private String msg;
    private List<UserInfo> retContent;
    private UserInfo[] retContent2;

}
package com.xgit.work.common.third.test;


import java.io.Serializable;

import lombok.Data;
/**
 * @ClassName:User
 * @Description:测试实体
 * @author Jerry
 * @date:2018年4月10日下午3:57:38
 */
@Data
public class UserInfo implements Serializable{

    private static final long serialVersionUID = -8842980384133458171L;
    private String            fid;
    private String            fnumber;
    private String fname;
 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值