package com.yihu.jw.utils;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.namespace.QName;
import java.util.Map;


/**
 * Created by hzp on 2017/7/31.
 * webservice调用服务
 **/
public class WebserviceUtil {

    private static Logger logger = LoggerFactory.getLogger(WebserviceUtil.class);


    /**
     * webservice 调用接口
     */
    public static String post(String urlString,String namespace,String api, Map<String,String> params) throws Exception {

        try {

            logger.info("ca_url:"+urlString);
            logger.info("ca_namespace:"+namespace);
            logger.info("api:"+api);
            Service service = new Service();
            logger.info("=======>通过service创建call对象");
            Call call = (Call) service.createCall();// 通过service创建call对象
            logger.info("=======>设置service所在URL");
            // 设置service所在URL
            call.setTargetEndpointAddress(new java.net.URL(urlString));
            call.setOperationName(new QName(namespace, api));
            call.setUseSOAPAction(true);
            Object[] objs = null;
            logger.info("=======>组装参数:"+params.size());
            if(params!=null && params.size()>0)
            {
                logger.info("=======>遍历参数");
                objs = new Object[params.size()];
                int i=0;
                for(String key : params.keySet())
                {
                    logger.info("=======>参数key:"+key);
                    logger.info("=======>接口参数:"+key);
                    call.addParameter(new QName(key), org.apache.axis.encoding.XMLType.XSD_STRING,javax.xml.rpc.ParameterMode.IN);//接口的参数
                    logger.info("=======>参数值:"+params.get(key));
                    objs[i] = params.get(key);
                    i++;
                }
            }
            logger.info("=======>设置返回类型");
            call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);//设置返回类型

            logger.info("=======>开始请求");
            String  ret = (String)call.invoke(objs);
            logger.info("=======>请求结果："+ret);
            logger.info("=======>请求结果.toString()："+ret.toString());
            return ret.toString();

        } catch (Exception e) {
            logger.info("=======>CA请求报错："+e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }

}
