Java生成C#可用Model包

项目需要提供接口给.NET团队使用,为方便大伙,特地写一个从Java接口生成C#可用Model包的工具Class

主Class是一个Controller,可以随时进行生成

package com.fang.microservice.cloud.controller;

import com.alibaba.druid.sql.visitor.functions.Char;
import com.fang.microservice.cloud.domain.MS_ServiceActionInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.annotation.Annotation;
import java.lang.reflect.*;
import java.math.BigDecimal;
import java.net.URLConnection;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Created by Administrator on 2017/5/11.
 */
@RestController
@ApiIgnore
public class CodeController {
    /**
     * 代码生成服务,创建C#访问代码
     *
     * @param request
     * @param platformCode
     * @param platformToken
     * @return
     */
    @RequestMapping(value = "/servicecodeforcsharp", method = {RequestMethod.GET, RequestMethod.POST})
    public void buildCodeFiles(HttpServletRequest request, HttpServletResponse response, String platformCode, String platformToken) throws IOException {
        //获取Web应用上下文
        WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());

        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();

        //创建临时目录
        String tempDirectoryName = UUID.randomUUID().toString();
        File tempDirectory = new File(tempDirectoryName);
        tempDirectory.mkdir();
        //复制文件到临时目录
        createResFile(wc, "ActionHandler.cs", tempDirectoryName);
        createResFile(wc, "NetUtility.cs", tempDirectoryName);
        createResFile(wc, "Proxy.cs", tempDirectoryName);

        //获取所有的Controller实例
        Map<String, Object> controllerBeans = wc.getBeansWithAnnotation(RestController.class);
        //遍历Controller实例,创建访问文件
        for (String beanKey : controllerBeans.keySet()) {
            //Controller映射访问路径
            String controllerBasePath = "";
            Object beanVal = controllerBeans.get(beanKey);
            Class beanClass = beanVal.getClass();
            //判断是否是可对外的Controller
            Annotation apiAnnotation = beanClass.getAnnotation(Api.class);
            if (apiAnnotation == null) {
                continue;
            }
            //判断是否忽略
            Annotation apiIgnoreAnnotation = beanClass.getAnnotation(ApiIgnore.class);
            if (apiIgnoreAnnotation != null) {
                continue;
            }
            //获取Controller基础地址
            RequestMapping requestMappingAnnotation = (RequestMapping) beanClass.getAnnotation(RequestMapping.class);
            if (requestMappingAnnotation != null) {
                String[] vals = requestMappingAnnotation.value();
                if (vals != null && vals.length > 0) {
                    controllerBasePath = vals[0];
                }
            }
            //创建Controller目录
            createDirectory(tempDirectoryName + "/" + controllerBasePath);
            //获取输入模型顶级目录
            String actionInModelDir = tempDirectoryName + "/" + controllerBasePath + "/In";
            //创建Controller目录.输入模型In
            createDirectory(actionInModelDir);
            //创建输出模型顶级目录
            String actionOutModelDir = tempDirectoryName + "/" + controllerBasePath + "/Out";
            //创建Controller目录.输出模型Out
            createDirectory(actionOutModelDir);

            //获取所有对外服务方法
            Method[] allMethods = beanClass.getDeclaredMethods();
            for (Method method : allMethods) {
                //识别是否可对外方法
                if (!method.isAnnotationPresent(RequestMapping.class)) {
                    continue;
                }
                //获取方法路径映射
                RequestMapping methodMappingAnnotation = method.getAnnotation(RequestMapping.class);
                //方法映射的访问地址
                String methodRelUri = "";
                String[] methodMappingVals = methodMappingAnnotation.value();
                if (methodMappingVals != null && methodMappingVals.length > 0) {
                    methodRelUri = methodMappingVals[0];
                }
                //获取方法名称描述
                String methodDescription = "";
                ApiOperation methodApiOption = method.getAnnotation(ApiOperation.class);
                if (methodApiOption != null && methodApiOption.value() != null && !methodApiOption.value().equals("")) {
                    methodDescription = methodApiOption.value();
                }
                //方法的完整地址
                String methodActionUri = controllerBasePath + methodRelUri;
                //获取方法输入参数
                Parameter[] methodParameters = method.getParameters();
                //获取方法返回结果
                Class methodReturnClass = method.getReturnType();
                HashMap<String, String> params = new HashMap<>();
                String[] methodParameterNames = u.getParameterNames(method);
                int paramIndex = 0;
                for (Parameter param : methodParameters) {
                    params.put(methodParameterNames[paramIndex], getParameterTypeString(param, actionInModelDir));
                    paramIndex++;
                }
                //方法输出结果类型字符串
                String outputModelTypeString = methodReturnClass.getTypeName();
                buildModelCodeString(methodReturnClass, actionOutModelDir);

                appendServiceAction(methodActionUri, outputModelTypeString, params, methodDescription);
            }
        }
        buildService(tempDirectoryName);
        buildZipFile(tempDirectoryName, "CSharp.zip");
        tempDirectory.deleteOnExit();
        File downloadFile = new File("CSharp.zip");
        try {
            String mimeType = URLConnection.guessContentTypeFromName(downloadFile.getName());
            if (mimeType == null) {
                mimeType = "application/octet-stream";
            }
            response.setContentType(mimeType);
            String pathTmp = java.net.URLEncoder.encode("CSharp.zip", "UTF-8");
            response.setHeader("Content-Disposition", String.format("inline; filename=\"" + pathTmp + "\""));
            response.setContentLength((int) downloadFile.length());
            InputStream inputStream = new BufferedInputStream(new FileInputStream(downloadFile));
            FileCopyUtils.copy(inputStream, response.getOutputStream());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } finally {
            downloadFile.delete();
            tempDirectory.delete();
        }
    }

    private void buildModelCodeString(Class modelClass, String directoryName) {
        if (modelTypeList.contains(modelClass.getName())) {
            return;
        }
        modelTypeList.add(modelClass.getName());
        StringBuilder txt = new StringBuilder();
        txt.append("using System;").append("\r\n");
        txt.append("using System.Collections.Generic;").append("\r\n");
        txt.append("\r\n");
        String modelClassName = modelClass.getName();
        txt.append("namespace ").append(modelClassName.replace("." + modelClass.getSimpleName(), "")).append("\r\n");
        txt.append("{\r\n");
        txt.append("\tpublic class ").append(modelClass.getSimpleName()).append("\r\n");
        txt.append("\t{\r\n");
        for (Field field : modelClass.getDeclaredFields()) {
            try {
                txt.append("\t\tpublic ").append(getFieldTypeString(field, directoryName)).append(" ").append(field.getName()).append(" { get; set; }\r\n");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        txt.append("\t}\r\n");
        txt.append("}");
        buildAndSaveFile(directoryName + "/" + modelClass.getSimpleName() + ".cs", txt.toString());
    }

    /**
     * 检测和创建文件夹
     *
     * @param directoryName
     */
    private void createDirectory(String directoryName) {
        File directory = new File(directoryName);
        if (!directory.exists()) {
            directory.mkdirs();
        }
    }

    /**
     * 从资源文件创建公共访问文件
     *
     * @param wc
     * @param fileName
     * @param tempDirectoryName
     */
    private void createResFile(WebApplicationContext wc, String fileName, String tempDirectoryName) {
        try {
            PathMatchingResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = patternResolver.getResources("classpath*:csharp/" + fileName);
            if (resources != null && resources.length > 0) {
                InputStreamReader isr = new InputStreamReader(resources[0].getInputStream());
                File destActionHandlerFile = new File(tempDirectoryName + "/" + fileName);
                if (!destActionHandlerFile.exists()) {
                    destActionHandlerFile.createNewFile();
                }

                char[] fileBytes = new char[256];
                FileOutputStream fos = new FileOutputStream(destActionHandlerFile);
                OutputStreamWriter osw = new OutputStreamWriter(fos);
                int readCount = -1;
                do {
                    readCount = isr.read(fileBytes);
                    if (readCount > 0) {
                        osw.write(fileBytes, 0, readCount);
                    }
                } while (readCount > 0);
                osw.flush();
                osw.close();
                fos.flush();
                fos.close();
                isr.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 应用服务名称
     */
    @Value("${spring.application.name}")
    private String applicationName;

    /**
     * 获取应用服务短名称
     *
     * @return
     */
    private String getServiceName() {
        if (!applicationName.contains("-")) {
            return applicationName;
        }
        return applicationName.substring(applicationName.lastIndexOf('-') + 1);
    }

    /**
     * 创建和保存文件
     *
     * @param fileName
     * @param content
     */
    private void buildAndSaveFile(String fileName, String content) {
        File targetFile = new File(fileName);
        if (!targetFile.exists()) {
            try {
                targetFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        FileOutputStream outputStream;
        try {
            outputStream = new FileOutputStream(targetFile);
            OutputStreamWriter osw = new OutputStreamWriter(outputStream);
            osw.write(content);
            osw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 把基础类型名称从Java转换为C#
     *
     * @param field              实体字段
     * @param modelDirectoryName 实体存储目录
     * @return
     */
    private String getFieldTypeString(Field field, String modelDirectoryName) {
        Class fieldClass = field.getType();
        if (fieldClass.equals(Integer.class) || fieldClass.equals(int.class)) {
            return "int";
        } else if (fieldClass.equals(Long.class) || fieldClass.equals(long.class)) {
            return "long";
        } else if (fieldClass.equals(BigDecimal.class)) {
            return "decimal";
        } else if (fieldClass.equals(Byte.class) || fieldClass.equals(byte.class)) {
            return "byte";
        } else if (fieldClass.equals(Short.class) || fieldClass.equals(short.class)) {
            return "short";
        } else if (fieldClass.equals(Float.class) || fieldClass.equals(Float.class)) {
            return "float";
        } else if (fieldClass.equals(Double.class) || fieldClass.equals(double.class)) {
            return "double";
        } else if (fieldClass.equals(Boolean.class) || fieldClass.equals(boolean.class)) {
            return "bool";
        } else if (fieldClass.equals(Char.class) || fieldClass.equals(char.class)) {
            return "char";
        } else if (fieldClass.equals(String.class)) {
            return "string";
        } else if (fieldClass.equals(Date.class)) {
            return "DateTime";
        } else if (fieldClass.equals(Object.class)) {
            return "object";
        } else {
            if (fieldClass.isAssignableFrom(List.class)) {
                Type fc = field.getGenericType();
                if (fc instanceof ParameterizedType) // 【3】如果是泛型参数的类型
                {
                    ParameterizedType pt = (ParameterizedType) fc;
                    Type[] genericTypes = pt.getActualTypeArguments();
                    if (genericTypes != null && genericTypes.length > 0) {
                        Class genericClazz = (Class) genericTypes[0]; //【4】 得到泛型里的class类型对象。
                        if (!genericClazz.isPrimitive() && !genericClazz.equals(String.class) && !genericClazz.equals(Date.class) && !genericClazz.equals(BigDecimal.class) && !genericClazz.equals(String.class)) {
                            buildModelCodeString(genericClazz, modelDirectoryName);
                        }
                        return "List<" + genericClazz.getName() + ">";
                    } else {
                        return "List<" + fc.getTypeName() + ">";
                    }
                } else {
                    return "List<" + fc.getClass().getName() + ">";
                }
            } else {
                String className = fieldClass.getName();
                buildModelCodeString(fieldClass, modelDirectoryName);
                return className;
            }
        }
    }

    /**
     * 把基础类型名称从Java转换为C#
     *
     * @param param              方法参数
     * @param modelDirectoryName 实体存储目录
     * @return
     */
    private String getParameterTypeString(Parameter param, String modelDirectoryName) {
        Class parameterClass = param.getType();
        if (parameterClass.equals(Integer.class) || parameterClass.equals(int.class)) {
            return "int";
        } else if (parameterClass.equals(Long.class) || parameterClass.equals(long.class)) {
            return "long";
        } else if (parameterClass.equals(BigDecimal.class)) {
            return "decimal";
        } else if (parameterClass.equals(Byte.class) || parameterClass.equals(byte.class)) {
            return "byte";
        } else if (parameterClass.equals(Short.class) || parameterClass.equals(short.class)) {
            return "short";
        } else if (parameterClass.equals(Float.class) || parameterClass.equals(Float.class)) {
            return "float";
        } else if (parameterClass.equals(Double.class) || parameterClass.equals(double.class)) {
            return "double";
        } else if (parameterClass.equals(Boolean.class) || parameterClass.equals(boolean.class)) {
            return "bool";
        } else if (parameterClass.equals(Char.class) || parameterClass.equals(char.class)) {
            return "char";
        } else if (parameterClass.equals(String.class)) {
            return "string";
        } else if (parameterClass.equals(Date.class)) {
            return "DateTime";
        } else if (parameterClass.equals(Object.class)) {
            return "object";
        } else {
            if (parameterClass.isAssignableFrom(List.class)) {
                Type fc = param.getType();
                if (fc instanceof ParameterizedType) // 【3】如果是泛型参数的类型
                {
                    ParameterizedType pt = (ParameterizedType) fc;
                    Type[] genericTypes = pt.getActualTypeArguments();
                    if (genericTypes != null && genericTypes.length > 0) {
                        Class genericClazz = (Class) genericTypes[0]; //【4】 得到泛型里的class类型对象。
                        if (!genericClazz.isPrimitive() && !genericClazz.equals(String.class) && !genericClazz.equals(Date.class) && !genericClazz.equals(BigDecimal.class) && !genericClazz.equals(String.class)) {
                            buildModelCodeString(genericClazz, modelDirectoryName);
                        }
                        return "List<" + genericClazz.getName() + ">";
                    } else {
                        return "List<" + fc.getTypeName() + ">";
                    }
                } else {
                    return "List<" + fc.getClass().getName() + ">";
                }
                //buildModelCodeString(parameterClass, modelDirectoryName);
                //return "List<" + parameterClass.getName() + ">";
            } else {
                String className = parameterClass.getName();
                buildModelCodeString(parameterClass, modelDirectoryName);
                return className;
            }
        }
    }

    /**
     * 服务Action列表
     */
    private ArrayList<MS_ServiceActionInfo> serviceActionList = new ArrayList();

    /**
     * 添加服务Action到列表中
     *
     * @param serviceUri
     * @param outputModelType
     * @param params
     */
    private void appendServiceAction(String serviceUri, String outputModelType, HashMap<String, String> params, String methodDescription) {
        MS_ServiceActionInfo sai = new MS_ServiceActionInfo();
        sai.setTargetUri(serviceUri);
        sai.setOutputModel(outputModelType);
        sai.setParamsDic(params);
        sai.setActionDescription(methodDescription);
        serviceActionList.add(sai);
    }

    /**
     * 构建访问服务
     *
     * @param tempDirectoryName 文件临时目录名称
     */
    private void buildService(String tempDirectoryName) {
        StringBuilder txt = new StringBuilder();
        txt.append("using System;").append("\r\n");
        txt.append("using Fang.Contract.WebUtil;").append("\r\n");
        txt.append("\r\n");
        txt.append("namespace Fang.Contract.Biz.").append(getServiceName()).append("\r\n");
        txt.append("{\r\n");
        txt.append("\tpublic class Service\r\n");
        txt.append("\t{\r\n");
        for (MS_ServiceActionInfo sai : serviceActionList) {
            txt.append("\t\t/// <summary>\r\n");
            txt.append("\t\t/// ").append(sai.getActionDescription()).append("\r\n");
            txt.append("\t\t/// </summary>\r\n");
            txt.append("\t\tpublic static ").append(sai.getOutputModel()).append(" ").append(sai.buildMethodName()).append("(").append(sai.buildMethodDefineParameters()).append(")\r\n");
            txt.append("\t\t{\r\n");
            if (sai.getParamsDic().keySet().size() == 1) {
                String parameterType = sai.getFirstParameterType();
                String parameterName = sai.getFirstParameterName();

                if (parameterType.contains(".")) {
                    txt.append("\t\t\treturn Proxy.ExecHandler.GetResponseModel<" + sai.getOutputModel() + ">(\"" + applicationName + "\", \"" + sai.getTargetUri() + "\", " + parameterName + ");\r\n");
                } else {
                    txt.append("\t\t\tstring PostData = ").append(sai.buildPostDataCode()).append(";\r\n");
                    txt.append("\t\t\treturn Proxy.ExecHandler.GetResponseModel<" + sai.getOutputModel() + ">(\"" + applicationName + "\", \"" + sai.getTargetUri() + "\", PostData);\r\n");
                }
            } else if (sai.getParamsDic().keySet().size() > 1) {
                txt.append("\t\t\tstring PostData = ").append(sai.buildPostDataCode()).append(";\r\n");
                txt.append("\t\t\treturn Proxy.ExecHandler.GetResponseModel<" + sai.getOutputModel() + ">(\"" + applicationName + "\", \"" + sai.getTargetUri() + "\", PostData);\r\n");
            }

            txt.append("\t\t}\r\n");
        }
        txt.append("\t}\r\n");
        txt.append("}");

        buildAndSaveFile(tempDirectoryName + "/" + "Service.cs", txt.toString());
    }

    private ArrayList<String> modelTypeList = new ArrayList<>();

    public void buildZipFile(String sourceDIR, String targetZipFile) {
        File targetFile = new File(targetZipFile);
        if (!targetFile.exists()) {
            try {
                targetFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        zip(targetZipFile, new File(sourceDIR));
    }

    public boolean zip(String zipFileName, File... files) {
        ZipOutputStream out = null;
        BufferedOutputStream bo = null;
        try {
            createDir(zipFileName);
            out = new ZipOutputStream(new FileOutputStream(zipFileName));
            for (int i = 0; i < files.length; i++) {
                if (null != files[i]) {
                    zip(out, files[i], files[i].getName());
                }
            }
            // 输出流关闭
            out.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 目录不存在时,先创建目录
     *
     * @param zipFileName
     */
    private static void createDir(String zipFileName) {
        String filePath = StringUtils.substringBeforeLast(zipFileName, "/");
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            //目录不存在时,先创建目录
            targetFile.mkdirs();
        }
    }

    /**
     * 执行压缩
     *
     * @param out  ZIP输入流
     * @param f    被压缩的文件
     * @param base 被压缩的文件名
     */
    private static void zip(ZipOutputStream out, File f, String base) {
        try {
            //压缩目录
            if (f.isDirectory()) {
                try {
                    File[] fl = f.listFiles();
                    // 创建zip实体
                    if (fl.length == 0) {
                        out.putNextEntry(new ZipEntry(base + "/"));
                    }
                    // 递归遍历子文件夹
                    for (int i = 0; i < fl.length; i++) {
                        zip(out, fl[i], base + "/" + fl[i].getName());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                //压缩单个文件
                out.putNextEntry(new ZipEntry(base));
                // 创建zip实体
                FileInputStream in = new FileInputStream(f);
                BufferedInputStream bi = new BufferedInputStream(in);
                int b;
                while ((b = bi.read()) != -1) {
                    // 将字节流写入当前zip目录
                    out.write(b);
                }
                //关闭zip实体
                out.closeEntry();
                // 输入流关闭
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

  

其中使用的Domain

package com.fang.microservice.cloud.domain;

import java.util.HashMap;

/**
 * Created by Administrator on 2017/5/9.
 */
public class MS_ServiceActionInfo {
    private String targetUri;

    private String outputModel;

    private HashMap<String, String> paramsDic = new HashMap<>();

    private String actionDescription;

    public String getTargetUri() {
        return targetUri;
    }

    public void setTargetUri(String targetUri) {
        this.targetUri = targetUri;
    }

    public String getOutputModel() {
        return outputModel;
    }

    public void setOutputModel(String outputModel) {
        this.outputModel = outputModel;
    }

    public HashMap<String, String> getParamsDic() {
        return paramsDic;
    }

    public void setParamsDic(HashMap<String, String> paramsDic) {
        this.paramsDic = paramsDic;
    }

    public String getActionDescription() {
        return actionDescription;
    }

    public void setActionDescription(String actionDescription) {
        this.actionDescription = actionDescription;
    }

    /**
     * 构建请求方法名
     * @return
     */
    public String buildMethodName() {
        String tempName = targetUri.replace("/", "_");
        if (targetUri.startsWith("/")) {
            tempName = tempName.substring(1);
        }
        tempName = tempName.substring(0, 1).toUpperCase() + tempName.substring(1);
        return tempName;
    }

    /**
     * 构建POST数据
     * @return
     */
    public String buildPostDataCode() {
        StringBuilder txt = new StringBuilder();
        int paramIndex = 0;
        for (String paramName : paramsDic.keySet()) {
            paramIndex++;
            if (paramIndex < paramsDic.keySet().size()) {
                txt.append("\"").append(paramName).append("=\"").append(" + ").append(paramName).append(" + \"&\" + ");
            } else {
                txt.append("\"").append(paramName).append("=\"").append(" + ").append(paramName);
            }
        }
        return txt.toString();
    }

    /**
     * 构建方法请求列表
     * @return
     */
    public String buildMethodCallParameters(){
        StringBuilder txt = new StringBuilder();
        int paramIndex = 0;
        for (String paramName : paramsDic.keySet()) {
            paramIndex++;
            if (paramIndex < paramsDic.keySet().size()) {
                txt.append(paramName).append(", ");
            } else {
                txt.append(paramName);
            }
        }
        return txt.toString();
    }

    /**
     * 构建方法定义参数列表
     * @return
     */
    public String buildMethodDefineParameters(){
        StringBuilder txt = new StringBuilder();
        int paramIndex = 0;
        for (String paramName : paramsDic.keySet()) {
            paramIndex++;
            if (paramIndex < paramsDic.keySet().size()) {
                txt.append(paramsDic.get(paramName)).append(" ").append(paramName).append(", ");
            } else {
                txt.append(paramsDic.get(paramName)).append(" ").append(paramName);
            }
        }
        return txt.toString();
    }

    /**
     * 在参数唯一时获取参数类型
     * @return
     */
    public String getFirstParameterType(){
        for(String paramName : paramsDic.keySet()){
            return paramsDic.get(paramName);
        }
        return "";
    }

    /**
     * 在参数唯一时获取参数名
     * @return
     */
    public String getFirstParameterName(){
        for(String paramName : paramsDic.keySet()){
            return paramName;
        }
        return "";
    }
}

  

实际场景:

在Spring Cloud项目中,Zuul网关定制一个界面,提供所有服务的聚合列表,列表中提供每一个服务可用接口Model生成地址,该地址指向本文中Controller中的生成地址,对接方可在页面上直接获取到调用服务所用的C#版本Model的Zip压缩包,直接解压缩到本地项目即可使用。

 

为方便C#同事使用,特提供C#版本访问代理工具类(因本人曾是C#程序员)

using System;
using System.Collections.Generic;

namespace Fang.Contract.WebUtil
{
    /// <summary>
    /// 服务环境标识
    /// </summary>
    public enum EnviormentEnum
    {
        /// <summary>
        /// 测试环境
        /// </summary>
        test,
        /// <summary>
        /// 生产环境
        /// </summary>
        prod
    }
    public class ActionHandler
    {
        /// <summary>
        /// 请求环境
        /// </summary>
        private EnviormentEnum ServiceEnviorment
        {
            get; set;
        }
        /// <summary>
        /// 系统请求基础域名
        /// </summary>
        private string ServiceDomain
        {
            get
            {
                if (ServiceEnviorment == EnviormentEnum.test)
                {
                    return "zuul.center.contract.microservice.test.fang.com";
                }
                else if (ServiceEnviorment == EnviormentEnum.prod)
                {
                    return "zuul.contract.microservice.ggpt.fang.com";
                }
                else
                {
                    return string.Empty;
                }
            }
        }
        /// <summary>
        /// 请求平台名称
        /// </summary>
        public string PlatformCode = "WEB";
        /// <summary>
        /// 请求平台令牌
        /// </summary>
        public string PlatformToken = "f13f6f52-28b0-11e7-9269-a0423f2f18c8";
        /// <summary>
        /// 请求认证Header
        /// </summary>
        private Dictionary<string, string> PlatformHeader = new Dictionary<string, string>();
        /// <summary>
        /// 服务�?
        /// </summary>
        public string ServiceId { get; set; }
        /// <summary>
        /// 服务地址
        /// </summary>
        public object ServiceUrl { get; set; }
        public ActionHandler()
        {

        }
        public ActionHandler(EnviormentEnum _Enviroment, string _PlatformCode, string _PlatformToken)
        {
            this.ServiceEnviorment = _Enviroment;
            this.PlatformCode = _PlatformCode;
            this.PlatformToken = _PlatformToken;
            this.PlatformHeader.Add(this.PlatformCode, this.PlatformToken);
        }

        private string BuildServiceUri()
        {
            return "http://" + ServiceDomain + "/" + ServiceId + "/" + ServiceUrl;
        }
        /// <summary>
        /// 获得字符串数�?
        /// </summary>
        /// <param name="ServiceId">服务Id</param>
        /// <param name="ServiceUrl">服务地址</param>
        /// <param name="RequestModel">输入实体</param>
        /// <returns></returns>
        public string GetResponseString(string ServiceId, string ServiceUrl, object RequestModel)
        {
            NetUtility wu = new NetUtility();
            string requestText = Newtonsoft.Json.JsonConvert.SerializeObject(RequestModel);
            string url = BuildServiceUri();
            string responseText = wu.DoPost(url, requestText, this.PlatformHeader);
            return responseText;
        }
        /// <summary>
        /// 获得字符串数�?
        /// </summary>
        /// <param name="ServiceId">服务Id</param>
        /// <param name="ServiceUrl">服务地址</param>
        /// <param name="PostData">输入文本</param>
        /// <returns></returns>
        public string GetResponseString(string ServiceId, string ServiceUrl, string PostData)
        {
            NetUtility wu = new NetUtility();
            string requestText = PostData;
            string url = BuildServiceUri();
            string responseText = wu.DoPost(url, requestText, this.PlatformHeader);
            return responseText;
        }
        /// <summary>
        /// 获得实体对象
        /// </summary>
        /// <typeparam name="T">输出实体类型</typeparam>
        /// <param name="ServiceId">服务Id</param>
        /// <param name="ServiceUrl">服务地址</param>
        /// <param name="RequestModel">输入实体</param>
        /// <returns></returns>
        public T GetResponseModel<T>(string ServiceId, string ServiceUrl, object RequestModel)
        {
            try
            {
                string data = GetResponseString(ServiceId, ServiceUrl, RequestModel);
                if (string.IsNullOrEmpty(data))
                {
                    return default(T);
                }
                return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(data);
            }
            catch (Exception)
            {
                return default(T);
            }
        }

        /// <summary>
        /// 获得实体对象
        /// </summary>
        /// <typeparam name="T">输出实体类型</typeparam>
        /// <param name="ServiceId">服务Id</param>
        /// <param name="ServiceUrl">服务地址</param>
        /// <param name="RequestModel">输入实体</param>
        /// <returns></returns>
        public T GetResponseModel<T>(string ServiceId, string ServiceUrl, string PostData)
        {
            try
            {
                string data = GetResponseString(ServiceId, ServiceUrl, PostData);
                if (string.IsNullOrEmpty(data))
                {
                    return default(T);
                }
                return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(data);
            }
            catch (Exception)
            {
                return default(T);
            }
        }
    }
}

  

using Fang.Contract.WebUtil;

namespace Fang.Contract.Biz
{
    public class Proxy
    {
        private static ActionHandler handler;

        public static ActionHandler ExecHandler
        {
            get
            {
                if (handler == null)
                {
                    handler = new ActionHandler(EnviormentEnum.test, "", "");
                }
                return handler;
            }
        }
    }
}

  

using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Text;

namespace Fang.Contract.WebUtil
{
    /// <summary>
    /// 网络工具类
    /// </summary>
    [Description("网络工具类")]
    public sealed class NetUtility
    {
        /// <summary>
        /// 请求超时时间
        /// </summary>
        private int _timeout = 100000;

        /// <summary>
        /// 请求与响应的超时时间
        /// </summary>
        public int Timeout
        {
            get { return this._timeout; }
            set { this._timeout = value; }
        }

        #region POST请求
        /// <summary>
        /// 执行HTTP POST请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="parameters">请求参数</param>
        /// <returns>HTTP响应</returns>
        public string DoPost(string url, string postText, Dictionary<string, string> headers)
        {
            try
            {
                HttpWebRequest req = GetWebRequest(url, "POST");
                req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
                if (headers != null && headers.Count > 0)
                {
                    foreach (string key in headers.Keys)
                    {
                        req.Headers.Add(key, headers[key]);
                    }
                }

                byte[] postData = Encoding.UTF8.GetBytes(postText);
                Stream reqStream = req.GetRequestStream();
                reqStream.Write(postData, 0, postData.Length);
                reqStream.Close();
                HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
                Encoding encoding = Encoding.GetEncoding("utf-8");
                return GetResponseAsString(rsp, encoding);
            }
            catch
            {
                return string.Empty;
            }
        }
        #endregion

        /// <summary>
        /// 获取HTTP请求对象
        /// </summary>
        /// <param name="url"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        public HttpWebRequest GetWebRequest(string url, string method)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.ServicePoint.Expect100Continue = false;
            req.Method = method;
            req.KeepAlive = true;
            req.UserAgent = "";
            req.Timeout = this._timeout;
            req.ReadWriteTimeout = this._timeout;
            return req;
        }

        /// <summary>
        /// 把响应流转换为文本
        /// </summary>
        /// <param name="rsp">响应流对象</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>响应文本</returns>
        public string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
        {
            Stream stream = null;
            StreamReader reader = null;

            try
            {
                // 以字符流的方式读取HTTP响应
                stream = rsp.GetResponseStream();
                reader = new StreamReader(stream, encoding);
                return reader.ReadToEnd();
            }
            finally
            {
                // 释放资源
                if (reader != null) reader.Close();
                if (stream != null) stream.Close();
                if (rsp != null) rsp.Close();
            }
        }
    }
}

  

posted @ 2018-07-31 11:04  仲卿  阅读(179)  评论(0编辑  收藏  举报