WebServiceAgent.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  1. using System;
  2. using System.CodeDom;
  3. using System.CodeDom.Compiler;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using System.Collections.Specialized;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Net;
  10. using System.Net.Http;
  11. using System.Net.Http.Headers;
  12. using System.Reflection;
  13. using System.Text;
  14. using System.Web.Script.Serialization;
  15. using System.Web.Services.Description;
  16. using System.Xml;
  17. namespace BaseLibComm
  18. {
  19. /// <summary>
  20. /// WebService 代理类
  21. /// </summary>
  22. public class WebServiceAgent
  23. {
  24. private object agent;
  25. private Type agentType;
  26. private const string CODE_NAMESPACE = "WebServiceAgent.Dynamic";
  27. private static jsonVMI[] vMI;
  28. /// <summary<
  29. /// Constructor
  30. /// </summary<
  31. /// <param name="url"<</param<
  32. public WebServiceAgent(string url)
  33. {
  34. try
  35. {
  36. XmlTextReader reader = new XmlTextReader(url + "?wsdl");
  37. //建立 WSDL格式文档
  38. ServiceDescription sd = ServiceDescription.Read(reader);
  39. //客户端代理
  40. ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
  41. sdi.AddServiceDescription(sd, null, null);
  42. //使用CodeDom 动态编译代理类
  43. CodeNamespace cn = new CodeNamespace(CODE_NAMESPACE);
  44. CodeCompileUnit ccu = new CodeCompileUnit();
  45. ccu.Namespaces.Add(cn);
  46. sdi.Import(cn, ccu);
  47. Microsoft.CSharp.CSharpCodeProvider icc = new Microsoft.CSharp.CSharpCodeProvider();
  48. CompilerParameters cp = new CompilerParameters();
  49. CompilerResults cr = icc.CompileAssemblyFromDom(cp, ccu);
  50. agentType = cr.CompiledAssembly.GetTypes()[0];
  51. agent = Activator.CreateInstance(agentType);
  52. WriteTextLog("日志", "初始化成功", DateTime.Now);
  53. }
  54. catch (Exception ex)
  55. {
  56. WriteTextLog("错误", ex.ToString(), DateTime.Now);
  57. throw;
  58. }
  59. }
  60. ///<summary>
  61. ///调用指定的方法
  62. ///</summary>
  63. ///<param name="methodName">方法名</param>
  64. ///<param name="args">动态参数</param>
  65. ///<returns>返回 Web service</returns>
  66. public string Invoke(string methodName, string args)
  67. {
  68. try
  69. {
  70. MethodInfo mi = agentType.GetMethod(methodName);
  71. ParameterInfo[] arrpi = mi.GetParameters();
  72. var pars = args.Trim().Split(',');
  73. ArrayList arr = new ArrayList();
  74. for (int i = 0; i < pars.Length; i++)
  75. {
  76. if (arrpi[i].ParameterType != typeof(string))
  77. {
  78. arr.Add(Convert.ChangeType(pars[i], arrpi[i].ParameterType));
  79. }
  80. else
  81. {
  82. arr.Add(pars[i].Replace("#",","));
  83. }
  84. }
  85. object ob = this.Invoke(mi, arr.ToArray());
  86. WriteTextLog("日志", ob.ToString(), DateTime.Now);
  87. return ob.ToString();
  88. }
  89. catch (Exception ex)
  90. {
  91. WriteTextLog("错误", ex.ToString(), DateTime.Now);
  92. throw;
  93. }
  94. }
  95. /// <summary>
  96. /// 调用指定的方法
  97. /// </summary>
  98. /// <param name="split">分隔符号</param>
  99. /// <param name="methodName">方法名</param>
  100. /// <param name="args">动态参数</param>
  101. /// <returns></returns>
  102. public string Invoke(string split, string methodName, string args)
  103. {
  104. try
  105. {
  106. MethodInfo mi = agentType.GetMethod(methodName);
  107. ParameterInfo[] arrpi = mi.GetParameters();
  108. var pars = args.Trim().Split(new[] { split }, StringSplitOptions.None);
  109. ArrayList arr = new ArrayList();
  110. for (int i = 0; i < pars.Length; i++)
  111. {
  112. if (arrpi[i].ParameterType != typeof(string))
  113. {
  114. arr.Add(Convert.ChangeType(pars[i], arrpi[i].ParameterType));
  115. }
  116. else
  117. {
  118. arr.Add(pars[i]);
  119. }
  120. }
  121. object ob = this.Invoke(mi, arr.ToArray());
  122. WriteTextLog("日志", ob.ToString(), DateTime.Now);
  123. return ob.ToString();
  124. }
  125. catch (Exception ex)
  126. {
  127. WriteTextLog("错误", ex.ToString(), DateTime.Now);
  128. throw;
  129. }
  130. }
  131. ///<summary>
  132. ///调用方法
  133. ///</summary>
  134. ///<param name="method">方法</param>
  135. ///<param name="args">参数</param>
  136. ///<returns>返回 Web service</returns>
  137. public object Invoke(MethodInfo method, params object[] args)
  138. {
  139. return method.Invoke(agent, args);
  140. }
  141. public MethodInfo[] Methods
  142. {
  143. get
  144. {
  145. return agentType.GetMethods();
  146. }
  147. }
  148. /// <summary>
  149. /// 写入日志到文本文件
  150. /// </summary>
  151. /// <param name="action">动作</param>
  152. /// <param name="strMessage">日志内容</param>
  153. /// <param name="time">时间</param>
  154. public static void WriteTextLog(string action, string strMessage, DateTime time)
  155. {
  156. string path = AppDomain.CurrentDomain.BaseDirectory + @"NetLog\";
  157. if (!Directory.Exists(path))
  158. Directory.CreateDirectory(path);
  159. string fileFullPath = path + time.ToString("yyyyMMdd") + ".txt";
  160. StringBuilder str = new StringBuilder();
  161. str.Append("Time: " + time.ToString() + "\r\n");
  162. str.Append("Action: " + action + "\r\n");
  163. str.Append("Message: " + strMessage + "\r\n");
  164. str.Append("-----------------------------------------------------------\r\n");
  165. StreamWriter sw;
  166. if (!File.Exists(fileFullPath))
  167. {
  168. sw = File.CreateText(fileFullPath);
  169. }
  170. else
  171. {
  172. sw = File.AppendText(fileFullPath);
  173. }
  174. sw.WriteLine(str.ToString());
  175. sw.Close();
  176. }
  177. /// <summary>
  178. /// 以Post方式提交命令
  179. /// </summary>
  180. public static string Post(string apiurl, string jsonString)
  181. {
  182. return Post(apiurl, jsonString, "utf-8");
  183. }
  184. /// <summary>
  185. /// 以Post方式提交命令
  186. /// </summary>
  187. public static string Post(string apiurl, string jsonString, string codingName)
  188. {
  189. try
  190. {
  191. WebRequest request = WebRequest.Create(@apiurl);
  192. request.Method = "POST";
  193. request.ContentType = "application/json";
  194. byte[] bs = Encoding.UTF8.GetBytes(jsonString);
  195. request.ContentLength = bs.Length;
  196. Stream newStream = request.GetRequestStream();
  197. newStream.Write(bs, 0, bs.Length);
  198. newStream.Close();
  199. WebResponse response = request.GetResponse();
  200. Stream stream = response.GetResponseStream();
  201. StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(codingName));
  202. string resultJson = reader.ReadToEnd();
  203. return resultJson;
  204. //string Url, string postDataStr
  205. //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
  206. //request.Method = "POST";
  207. //request.ContentType = "application/x-www-form-urlencoded";
  208. //request.ContentLength = postDataStr.Length;
  209. //StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII);
  210. //writer.Write(postDataStr);
  211. //writer.Flush();
  212. //HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  213. //string encoding = response.ContentEncoding;
  214. //if (encoding == null || encoding.Length < 1)
  215. //{
  216. // encoding = "UTF-8"; //默认编码
  217. //}
  218. //StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
  219. //string retString = reader.ReadToEnd();
  220. //return retString;
  221. }
  222. catch (Exception ex)
  223. {
  224. WriteTextLog("错误", ex.ToString(), DateTime.Now);
  225. throw;
  226. }
  227. }
  228. public static string Post(string url)
  229. {
  230. return PostByCoding(url, "utf-8");
  231. }
  232. public static string PostByCoding(string url, string codingName)
  233. {
  234. try
  235. {
  236. WebRequest request = WebRequest.Create(@url);
  237. byte[] bs = Encoding.UTF8.GetBytes(string.Empty);
  238. request.ContentType = "application/x-www-form-urlencoded";
  239. request.ContentLength = bs.Length;
  240. request.Method = "POST";
  241. System.IO.Stream RequestStream = request.GetRequestStream();
  242. RequestStream.Write(bs, 0, bs.Length);
  243. RequestStream.Close();
  244. System.Net.WebResponse response = request.GetResponse();
  245. StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(codingName));
  246. string ReturnVal = reader.ReadToEnd();
  247. reader.Close();
  248. response.Close();
  249. return ReturnVal;
  250. }
  251. catch (Exception ex)
  252. {
  253. WriteTextLog("错误", ex.ToString(), DateTime.Now);
  254. throw;
  255. }
  256. }
  257. /// <summary>
  258. /// Get方式提交
  259. /// </summary>
  260. /// <param name="url"></param>
  261. /// <returns></returns>
  262. public static string Get(string url)
  263. {
  264. return Get(url, "utf-8");
  265. }
  266. /// <summary>
  267. /// 异步Get
  268. /// </summary>
  269. /// <param name="url"></param>
  270. /// <returns></returns>
  271. public static string GetByHttpClient(string url)
  272. {
  273. HttpClient httpClient = new HttpClient();
  274. var response = httpClient.GetAsync(url).Result;
  275. string msg = response.Content.ReadAsStringAsync().Result;
  276. return msg;
  277. }
  278. /// <summary>
  279. /// 异步Post
  280. /// </summary>
  281. /// <param name="url"></param>
  282. /// <returns></returns>
  283. public static string PostByHttpClient(string url, string pars)
  284. {
  285. HttpClient httpClient = new HttpClient();
  286. MultipartFormDataContent form = new MultipartFormDataContent();
  287. string[] splits = pars.Split('&');
  288. foreach (var item in splits)
  289. {
  290. string[] keys = item.Split('=');
  291. string value = string.Empty;
  292. if (keys.Length > 1)
  293. {
  294. value = keys[1];
  295. }
  296. form.Add(new StringContent(value), keys[0]);
  297. }
  298. var response = httpClient.PostAsync(new Uri(url), form).Result;
  299. string msg = response.Content.ReadAsStringAsync().Result;
  300. return msg;
  301. }
  302. /// <summary>
  303. /// 文件下载
  304. /// </summary>
  305. /// <param name="url"></param>
  306. /// <param name="json">json字符串</param>
  307. /// <param name="filePath">文件保存路径</param>
  308. /// <returns></returns>
  309. public static string DownLoadByHttpClient(string url, string json, string filePath)
  310. {
  311. try
  312. {
  313. HttpClient httpClient = new HttpClient();
  314. StringContent content = new StringContent(json);
  315. content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
  316. var response = httpClient.PostAsync(new Uri(url), content).Result;
  317. var stream = response.Content.ReadAsStreamAsync().Result;
  318. StreamToFile(stream, filePath);
  319. return filePath;
  320. }
  321. catch (Exception ex)
  322. {
  323. WriteTextLog("错误", ex.ToString(), DateTime.Now);
  324. return "";
  325. }
  326. }
  327. /// <summary>
  328. /// VMI个案开发
  329. /// </summary>
  330. /// <param name="url"></param>
  331. /// <param name="filePath">保存的文件夹路径</param>
  332. /// <returns></returns>
  333. public static string DownLoadForVMI(string url, string filePath)
  334. {
  335. try
  336. {
  337. if (vMI == null)
  338. {
  339. return "";
  340. }
  341. else
  342. {
  343. JavaScriptSerializer js = new JavaScriptSerializer();
  344. string json = js.Serialize(vMI[0]);
  345. string result1=DownLoadByHttpClient(url + "/" + vMI[0].image, json, filePath+ vMI[0].image);
  346. json=js.Serialize(vMI[1]);
  347. string result2=DownLoadByHttpClient(url + "/" + vMI[1].image, json, filePath + vMI[1].image);
  348. vMI = null;
  349. return result1+","+ result2;
  350. }
  351. }
  352. catch (Exception ex)
  353. {
  354. WriteTextLog("错误", ex.ToString(), DateTime.Now);
  355. throw;
  356. }
  357. }
  358. /// <summary>
  359. /// 将 Stream 写入文件
  360. /// </summary>
  361. public static void StreamToFile(Stream stream, string fileName)
  362. {
  363. // 把 Stream 转换成 byte[]
  364. byte[] bytes = new byte[stream.Length];
  365. stream.Read(bytes, 0, bytes.Length);
  366. // 设置当前流的位置为流的开始
  367. stream.Seek(0, SeekOrigin.Begin);
  368. // 把 byte[] 写入文件
  369. FileStream fs = new FileStream(fileName, FileMode.Create);
  370. BinaryWriter bw = new BinaryWriter(fs);
  371. bw.Write(bytes);
  372. bw.Close();
  373. fs.Close();
  374. }
  375. /// <summary>
  376. /// Get方式提交
  377. /// </summary>
  378. /// <param name="url"></param>
  379. /// <param name="codingName">utf-8</param>
  380. /// <returns></returns>
  381. public static string Get(string url, string codingName)
  382. {
  383. try
  384. {
  385. // 设置参数
  386. HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
  387. CookieContainer cookieContainer = new CookieContainer();
  388. request.CookieContainer = cookieContainer;
  389. request.AllowAutoRedirect = true;
  390. request.Method = "GET";
  391. request.ContentType = "application/json";
  392. request.Headers.Add("charset", codingName);
  393. //发送请求并获取相应回应数据
  394. HttpWebResponse response = request.GetResponse() as HttpWebResponse;
  395. //直到request.GetResponse()程序才开始向目标网页发送Post请求
  396. Stream responseStream = response.GetResponseStream();
  397. StreamReader sr = new StreamReader(responseStream, Encoding.GetEncoding(codingName));
  398. //返回结果网页(html)代码
  399. string content = sr.ReadToEnd();
  400. return content;
  401. //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
  402. //request.Method = "GET";
  403. //request.ContentType = "text/html;charset=UTF-8";
  404. //HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  405. //Stream myResponseStream = response.GetResponseStream();
  406. //StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
  407. //string retString = myStreamReader.ReadToEnd();
  408. //myStreamReader.Close();
  409. //myResponseStream.Close();
  410. //return retString;
  411. }
  412. catch (Exception ex)
  413. {
  414. WriteTextLog("错误", ex.ToString(), DateTime.Now);
  415. throw;
  416. }
  417. }
  418. /// <summary>
  419. /// Post请求
  420. /// </summary>
  421. /// <param name="url"></param>
  422. /// <returns></returns>
  423. public static string PostData(string url, string Pars)
  424. {
  425. return PostData(url, Pars, "utf-8");
  426. }
  427. /// <summary>
  428. /// Post请求
  429. /// </summary>
  430. /// <param name="url"></param>
  431. /// <returns></returns>
  432. public static string PostData(string url, string Pars, string codingName)
  433. {
  434. try
  435. {
  436. WebRequest request = WebRequest.Create(@url);
  437. byte[] bs = Encoding.UTF8.GetBytes(Pars);
  438. request.ContentType = "application/x-www-form-urlencoded";
  439. request.ContentLength = bs.Length;
  440. request.Method = "POST";
  441. System.IO.Stream RequestStream = request.GetRequestStream();
  442. RequestStream.Write(bs, 0, bs.Length);
  443. RequestStream.Close();
  444. System.Net.WebResponse response = request.GetResponse();
  445. StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(codingName));
  446. string ReturnVal = reader.ReadToEnd();
  447. reader.Close();
  448. response.Close();
  449. return ReturnVal;
  450. }
  451. catch (Exception ex)
  452. {
  453. WriteTextLog("错误", ex.ToString(), DateTime.Now);
  454. throw;
  455. }
  456. }
  457. public static string UploadByWebClient(string url, string Pars, string fileFormName, string filePath)
  458. {
  459. return UploadByWebClient(url, Pars, filePath, "utf-8");
  460. }
  461. public static string UploadByWebClient(string url, string Pars, string fileFormName, string filePath, string codingName)
  462. {
  463. try
  464. {
  465. var webclient = new WebClient();
  466. NameValueCollection nvc = new NameValueCollection();
  467. string[] splits = Pars.Split('&');
  468. foreach (var item in splits)
  469. {
  470. string[] keys = item.Split('=');
  471. string value = string.Empty;
  472. if (keys.Length > 1)
  473. {
  474. value = keys[1];
  475. }
  476. nvc.Add(keys[0], value);
  477. }
  478. webclient.QueryString = nvc;
  479. byte[] buffer = webclient.UploadFile(url, "POST", filePath);
  480. var msg = Encoding.GetEncoding(codingName).GetString(buffer);
  481. return msg;
  482. }
  483. catch (Exception ex)
  484. {
  485. WriteTextLog("错误", ex.ToString(), DateTime.Now);
  486. throw;
  487. }
  488. }
  489. /// <summary>
  490. /// 上传图片
  491. /// </summary>
  492. /// <param name="url"></param>
  493. /// <param name="Pars"></param>
  494. /// <param name="fileFormName">服务端标记key(不是文件名)</param>
  495. /// <param name="filePath">文件路径</param>
  496. /// <returns></returns>
  497. public static string UploadPostData(string url, string Pars, string fileFormName, string filePath)
  498. {
  499. if (Directory.Exists(filePath))
  500. {
  501. filePath = Directory.GetFiles(filePath).First();
  502. }
  503. string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
  504. byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
  505. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  506. request.ContentType = "multipart/form-data; boundary=" + boundary;
  507. request.Method = "POST";
  508. /*wr.KeepAlive = true;
  509. wr.Credentials = System.Net.CredentialCache.DefaultCredentials;*/
  510. Stream rs = request.GetRequestStream();
  511. string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
  512. string[] splits = Pars.Split('&');
  513. foreach (var item in splits)
  514. {
  515. string[] keys = item.Split('=');
  516. string value = string.Empty;
  517. if (keys.Length > 1)
  518. {
  519. value = keys[1];
  520. }
  521. rs.Write(boundarybytes, 0, boundarybytes.Length);
  522. string formitem = string.Format(formdataTemplate, keys[0], value);
  523. byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
  524. rs.Write(formitembytes, 0, formitembytes.Length);
  525. }
  526. if (!string.IsNullOrEmpty(filePath))
  527. {
  528. rs.Write(boundarybytes, 0, boundarybytes.Length);
  529. /*string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
  530. string header = string.Format(headerTemplate, fileFormName, fileFormName, "text/html");*/
  531. string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n\r\n";
  532. string header = string.Format(headerTemplate, fileFormName, Path.GetFileName(filePath));
  533. byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
  534. rs.Write(headerbytes, 0, headerbytes.Length);
  535. //读取图片流
  536. byte[] byteFile = File.ReadAllBytes(filePath);
  537. rs.Write(byteFile, 0, byteFile.Length);
  538. }
  539. //结束分隔标记
  540. byte[] endBoundary = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
  541. rs.Write(endBoundary, 0, endBoundary.Length);
  542. rs.Close();
  543. WebResponse response = null;
  544. try
  545. {
  546. response = request.GetResponse();
  547. Stream stream2 = response.GetResponseStream();
  548. StreamReader reader2 = new StreamReader(stream2);
  549. string msg = reader2.ReadToEnd();
  550. return msg;
  551. }
  552. catch (Exception ex)
  553. {
  554. if (response != null)
  555. {
  556. response.Close();
  557. response = null;
  558. }
  559. return ex.ToString();
  560. }
  561. finally
  562. {
  563. request = null;
  564. }
  565. }
  566. /// <summary>
  567. /// 多文件上传
  568. /// </summary>
  569. /// <param name="url"></param>
  570. /// <param name="pars">附加参数格式:key=value&key=value</param>
  571. /// <param name="fileFormName">文件key多个用逗号分开</param>
  572. /// <param name="filePath">文件路径多个用逗号分开</param>
  573. /// <returns></returns>
  574. public static string UploadByHttpClient(string url, string pars, string fileFormName, string filePath)
  575. {
  576. try
  577. {
  578. HttpClient httpClient = new HttpClient();
  579. MultipartFormDataContent form = new MultipartFormDataContent();
  580. if (pars.Length > 0)
  581. {
  582. string[] splits = pars.Split('&');
  583. foreach (var item in splits)
  584. {
  585. string[] keys = item.Split('=');
  586. string value = string.Empty;
  587. if (keys.Length > 1)
  588. {
  589. value = keys[1];
  590. }
  591. form.Add(new StringContent(value), keys[0]);
  592. }
  593. }
  594. string[] fileFormNames = fileFormName.Split(',');
  595. string[] filePaths = filePath.Split(',');
  596. for (int i = 0; i < fileFormNames.Length; i++)
  597. {
  598. form.Add(new ByteArrayContent(File.ReadAllBytes(filePaths[i])), fileFormNames[i], Path.GetFileName(filePaths[i]));
  599. }
  600. var response = httpClient.PostAsync(new Uri(url), form).Result;
  601. WriteTextLog("状态", response.ToString(), DateTime.Now);
  602. string msg = response.Content.ReadAsStringAsync().Result;
  603. return msg;
  604. }
  605. catch (Exception ex)
  606. {
  607. WriteTextLog("错误", ex.ToString(), DateTime.Now);
  608. throw;
  609. }
  610. }
  611. public static string UploadByHttpClientForVMI(string url, string pars, string fileFormName, string filePath)
  612. {
  613. try
  614. {
  615. HttpClient httpClient = new HttpClient();
  616. MultipartFormDataContent form = new MultipartFormDataContent();
  617. if (pars.Length > 0)
  618. {
  619. string[] splits = pars.Split('&');
  620. foreach (var item in splits)
  621. {
  622. string[] keys = item.Split('=');
  623. string value = string.Empty;
  624. if (keys.Length > 1)
  625. {
  626. value = keys[1];
  627. }
  628. form.Add(new StringContent(value), keys[0]);
  629. }
  630. }
  631. string[] fileFormNames = fileFormName.Split(',');
  632. string[] filePaths = filePath.Split(',');
  633. for (int i = 0; i < fileFormNames.Length; i++)
  634. {
  635. if (filePaths[i].IndexOf(":")>-0 && filePaths[i].IndexOf(".")>0)
  636. {
  637. form.Add(new ByteArrayContent(File.ReadAllBytes(filePaths[i])), fileFormNames[i], Path.GetFileName(filePaths[i]));
  638. }
  639. else
  640. {
  641. form.Add(new StringContent(filePaths[i]), fileFormNames[i]);
  642. }
  643. }
  644. var response = httpClient.PostAsync(new Uri(url), form).Result;
  645. string str = response.ToString();
  646. str = str.Substring(0,str.IndexOf("Version")-2);
  647. WriteTextLog("状态", str, DateTime.Now);
  648. string msg = response.Content.ReadAsStringAsync().Result;
  649. //[{"elapsed_time":23.23218607902527,"front_new":0,"front_old":0,"image":"HZMC18102600WD_Pre_0120181027_083248_annotated.jpg","side":"FRONT","start_time":"2018-10-29 11:25:44.423392","token":"709c3ba8cf6ef60a80e44191cf58509c"},{"back_new":0,"back_old":0,"elapsed_time":23.23218607902527,"image":"HZMC18102600WD_Pre_0220181027_083304_annotated.jpg","side":"BACK","start_time":"2018-10-29 11:25:44.423392","token":"5ad24ec9fb478beab520c354c9d9bf3c"}]
  650. JavaScriptSerializer js = new JavaScriptSerializer();
  651. List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
  652. try
  653. {
  654. vMI = js.Deserialize<jsonVMI[]>(msg);
  655. list = js.Deserialize<List<Dictionary<string, object>>>(msg);
  656. foreach (var item in list)
  657. {
  658. item.Remove("image");
  659. item.Remove("token");
  660. item.Remove("side");
  661. }
  662. }
  663. catch
  664. {
  665. }
  666. WriteTextLog("记录", str + ";" + msg, DateTime.Now);
  667. return str + ";"+js.Serialize(list);
  668. }
  669. catch (Exception ex)
  670. {
  671. WriteTextLog("错误", ex.ToString(), DateTime.Now);
  672. throw;
  673. }
  674. }
  675. /// <summary>
  676. /// VMI个案开发
  677. /// </summary>
  678. /// <param name="url"></param>
  679. /// <param name="fileFormName">文件key多个用逗号分开</param>
  680. /// <param name="filePath">文件路径多个用逗号分开</param>
  681. /// <returns></returns>
  682. public static string UploadForVMI(string url, string fileFormName, string filePath)
  683. {
  684. try
  685. {
  686. string msg = UploadByHttpClientForVMI(url, "", fileFormName, filePath);
  687. return msg;
  688. }
  689. catch (Exception ex)
  690. {
  691. WriteTextLog("错误", ex.ToString(), DateTime.Now);
  692. throw;
  693. }
  694. }
  695. class jsonVMI
  696. {
  697. public int decision { get; set; }
  698. public string image { get; set; }
  699. public string side { get; set; }
  700. public string token { get; set; }
  701. }
  702. #region 格式
  703. //var objJson = new
  704. //{
  705. // unit_sn = dictStrAllData["unit_sn"],
  706. // serials = new
  707. // {
  708. // top_case = dictStrAllData["top_case"],
  709. // bottom_case = dictStrAllData["bottom_case"]
  710. // },
  711. // pass = dictStrAllData["pass"],
  712. // input_time = dictStrAllData["input_time"],
  713. // output_time = dictStrAllData["output_time"],
  714. // data = new
  715. // {
  716. // MeasurementA = dictStrAllData["MeasurementA"],
  717. // MeasurementB = dictStrAllData["MeasurementB"],
  718. // MeasurementC = dictStrAllData["MeasurementC"],
  719. // sw_version = dictStrAllData["sw_version"],
  720. // limits_version = dictStrAllData["limits_version"],
  721. // },
  722. // limits = new
  723. // {
  724. // MeasurementA = new
  725. // {
  726. // upper_limit = dictStrAllData["upper_limit_A"],
  727. // lower_limit = dictStrAllData["lower_limit_A"]
  728. // },
  729. // MeasurementB = new
  730. // {
  731. // upper_limit = dictStrAllData["upper_limit_B"]
  732. // },
  733. // MeasurementC = new
  734. // {
  735. // lower_limit = dictStrAllData["lower_limit_C"]
  736. // }
  737. // },
  738. // attr = new
  739. // {
  740. // ATTR1 = dictStrAllData["ATTR1"],
  741. // ATTR2 = dictStrAllData["ATTR2"]
  742. // },
  743. // blobs = new object[]
  744. // {
  745. // new { file_name = dictStrAllData["file_name_log"] },
  746. // new
  747. // {
  748. // file_name = dictStrAllData["file_name_image"],
  749. // retention_policy= dictStrAllData["retention_policy"]
  750. // }
  751. // }
  752. //};
  753. #endregion
  754. }
  755. }