項目須要提供接口給.NET團隊使用,爲方便大夥,特意寫一個從Java接口生成C#可用Model包的工具Classjava
主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(); } } }
其中使用的Domainweb
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
在Spring Cloud項目中,Zuul網關定製一個界面,提供全部服務的聚合列表,列表中提供每個服務可用接口Model生成地址,該地址指向本文中Controller中的生成地址,對接方可在頁面上直接獲取到調用服務所用的C#版本Model的Zip壓縮包,直接解壓縮到本地項目便可使用。sql
爲方便C#同事使用,特提供C#版本訪問代理工具類(因本人曾是C#程序員)apache
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(); } } } }