RailwayThirdTools.java 8.23 KB
package com.xiniunet.service.railway.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xiniunet.framework.base.BaseRequest;
import com.xiniunet.framework.cache.CacheManager;
import com.xiniunet.framework.constant.CacheTimeEnum;
import com.xiniunet.framework.log.LogUtil;
import com.xiniunet.framework.util.EncryptUtil;
import com.xiniunet.framework.util.SpringContext;
import com.xiniunet.railway.request.RailwayPostPositionRequest;
import com.xiniunet.service.railway.Constant;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.*;

public class RailwayThirdTools {
    private static Logger logger = LoggerFactory.getLogger(RailwayThirdTools.class);
    private static CacheManager cacheManager = SpringContext.getApplicationContext().getBean(CacheManager.class);

    public static Map<?, ?> objectToMap(Object obj) {
        if(obj == null)
            return null;

        return new org.apache.commons.beanutils.BeanMap(obj);
    }


    public static void main(String[] args) throws Exception{
        String url = "https://api.netease.im/nimserver/team/create.action";
        JSONArray members = new JSONArray();
        members.add(0,"sqqtalk");
        Map<String,String> params = new HashMap<String,String>();
        params.put("tname","teamsqq2");
        params.put("owner","sqqtalk2");
        params.put("members",members.toJSONString());
        params.put("msg","welcome to xntalk team");
        params.put("magree","1");
        params.put("joinmode","0");
        // 执行请求
        JSONObject jsonObject = railwayThird(true,url,params);

        // 打印执行结果
        System.out.println(jsonObject.toJSONString());
    }


    public static JSONObject railwayThird(Boolean fromCache,String url, BaseRequest request) throws IOException {
        String key=null;
        if(fromCache){
            key = EncryptUtil.MD5(url + JSON.toJSONString(request));
            Object value = cacheManager.get(key);
            if(value != null) {
                logger.warn("缓存命中");
                return JSON.parseObject(value.toString());
            }
            if(!url.equals(Constant.RALWAY_THIRD_SAFETY_ESCORT_POSITION_URL)) {
                logger.warn("缓存未命中," + url + "     " + JSON.toJSONString(request));
            }
        }

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        // 设置请求的header
        httpPost.addHeader("Content-Type", "application/json");
        httpPost.setEntity(new StringEntity( com.alibaba.fastjson.JSON.toJSONString(request)));
        // 执行请求
        long start =System.currentTimeMillis();
        HttpResponse response = httpClient.execute(httpPost);
        long end = System.currentTimeMillis();
        long count = end-start;
        logger.warn("=========纯粹调用 耗时===============:"+count );
        JSONObject result = (JSONObject) JSONObject.parse(EntityUtils.toString(response.getEntity(), "utf-8"));
        if(fromCache) {
            cacheManager.set(key, result.toJSONString(), CacheTimeEnum.FIVE_MINUTES);
        }
        result.put("timeCount",count);
        return result;
    }
    public static JSONObject railwayThirdWifi(String url, BaseRequest request) throws IOException {
        /*String key = EncryptUtil.MD5(url + JSON.toJSONString(request));
        Object value = cacheManager.get(key);
        if(value != null) {
            logger.warn("缓存命中");
            return JSON.parseObject(value.toString());
        }
        if(!url.equals(Constant.RALWAY_THIRD_SAFETY_ESCORT_POSITION_URL)) {
            logger.warn("缓存未命中," + url + "     " + JSON.toJSONString(request));
        }*/

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        // 设置请求的header
        httpPost.addHeader("Content-Type", "application/json");
        httpPost.addHeader("apikey", Constant.API_KEY);
        httpPost.addHeader("authorization", Constant.AUTHORIZATION);
        httpPost.setEntity(new StringEntity( com.alibaba.fastjson.JSON.toJSONString(request)));
        // 执行请求
        HttpResponse response = httpClient.execute(httpPost);
        JSONObject result = (JSONObject) JSONObject.parse(EntityUtils.toString(response.getEntity(), "utf-8"));
//        cacheManager.set(key, result.toJSONString(), CacheTimeEnum.ONE_MINUTE);
        return result;
    }


    public static Map ObjectToMap(Object obj){
        Map<String,Object> resultMap = new HashMap<String,Object>();
        Method[] methods = obj.getClass().getDeclaredMethods();
        for (Method method : methods) {
            try {
                if (method.getName().startsWith("get")) {
                    String field = method.getName();
                    field = field.substring(field.indexOf("get") + 3);
                    field = field.toLowerCase().charAt(0) + field.substring(1); // 转换成小写
                    Object value = method.invoke(obj, (Object[]) null);
                    if (value != null) {
                        resultMap.put(field, value.toString());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return resultMap;

    }




    public static JSONObject railwayThird(Boolean needCache,String url,Map<String,String> params) throws IOException {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        String nonce =  System.currentTimeMillis() + "" + new Random(System.currentTimeMillis()).nextInt(10000);
        String curTime = String.valueOf((new Date()).getTime() / 1000L);

        // 设置请求的header
        httpPost.addHeader("Nonce", nonce);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
        // 设置请求的参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            nvps.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
        }
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
        // 执行请求
        HttpResponse response = httpClient.execute(httpPost);
        JSONObject jsonObject = (JSONObject) JSONObject.parse(EntityUtils.toString(response.getEntity(), "utf-8"));
        return jsonObject;
    }

    public static JSONObject railwayThirdWebService(String url, BaseRequest request, String operationName, String paramName) throws IOException {
        JSONObject result = new JSONObject();
        try {
            String endpoint = url;
            String temp = JSON.toJSONString(request);
            // 直接引用远程的wsdl文件
            Service service = new Service();
            Call call = (Call) service.createCall();
            call.setTargetEndpointAddress(endpoint);
            call.setOperationName(operationName);// WSDL里面描述的接口名称
            call.addParameter(paramName,
                    org.apache.axis.encoding.XMLType.XSD_DATE,
                    javax.xml.rpc.ParameterMode.IN);// 接口的参数
            call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);// 设置返回类型
            call.invoke(new Object[] { temp });
            String a = (String)call.invoke(new Object[] { temp });
            result = JSON.parseObject(a);
        } catch (Exception e) {
            System.err.println(e.toString());
        }
        return result;
    }
}