caiyintongload.aspx.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  1. using BizCom;
  2. using ICSharpCode.SharpZipLib.Zip;
  3. using Newtonsoft.Json.Linq;
  4. using SiteCore.Redis;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Configuration;
  8. using System.Data;
  9. using System.Data.SqlClient;
  10. using System.IO;
  11. using System.Net.Security;
  12. using System.Net;
  13. using System.Text;
  14. using System.Web;
  15. using System.Web.UI;
  16. using System.Security.Cryptography.X509Certificates;
  17. using Utils;
  18. using System.Runtime.InteropServices;
  19. using NPOI.OpenXmlFormats.Shared;
  20. public partial class caiyingtongload : System.Web.UI.Page
  21. {
  22. public static string upPath = ConfigurationManager.AppSettings["upPath"];
  23. public static string copyPath = ConfigurationManager.AppSettings["copyPath"];
  24. public static string siteUrl = ConfigurationManager.AppSettings["OriSiteUrl"];
  25. [DllImport("DrvInterface64.dll", CharSet = CharSet.Unicode)]
  26. public static extern uint DecFile(string filename);
  27. [DllImport("DrvInterface64.dll", CharSet = CharSet.Unicode)]
  28. public static extern int IsFileEncrypted(string filename);//返回1为加密,0为未被加密
  29. [DllImport("DrvInterface64.dll", CharSet = CharSet.Ansi)]
  30. public static extern void CreateUserKey(StringBuilder key, int len);
  31. [DllImport("DrvInterface64.dll", CharSet = CharSet.Ansi)]
  32. public static extern int InitAesKey(StringBuilder key, int len);
  33. [DllImport("DrvInterface64.dll")]
  34. public static extern int IsInitedAesKey();
  35. private void conErc(string msg)
  36. {
  37. if (msg.IndexOf("访问远程主机") == -1)
  38. {
  39. XLog.SaveLog(0, msg);
  40. }
  41. Response.Write(msg);
  42. //Response.End();
  43. }
  44. private void conSuc(string msg)
  45. {
  46. Response.Write("{\"type\":\"success\",\"result\":\"" + msg + "\"}");
  47. //Response.End();
  48. }
  49. protected void Page_Load(object sender, EventArgs e)
  50. {
  51. if (!IsPostBack)
  52. {
  53. Response.Buffer = true;
  54. downloadcayingtonge();
  55. }
  56. }
  57. private string getCanDownFile(string fileName)
  58. {
  59. string[] extArr = new string[] { ".cdr", ".zip", ".rar" };
  60. foreach (string ext in extArr)
  61. {
  62. string fname = fileName + ext;
  63. if (File.Exists(fname))
  64. {
  65. return fname;
  66. }
  67. }
  68. return "";
  69. }
  70. private void updateIsDownSuccess(int userId, string ctid)
  71. {
  72. try
  73. {
  74. XLog.SaveLog(0, "updateIsDownSuccess ,ctid:" + ctid);
  75. SqlParameter[] sqlParameter ={
  76. new SqlParameter("@mainctids", SqlDbType.VarChar,500),
  77. new SqlParameter("@userid", SqlDbType.VarChar,4),
  78. new SqlParameter("@res", SqlDbType.VarChar, 4000)
  79. };
  80. sqlParameter[0].Value = ctid;
  81. sqlParameter[1].Value = userId;
  82. sqlParameter[2].Direction = ParameterDirection.Output;
  83. CeErpTradeCell.ExecuteDataSetStore("sp_set_download", sqlParameter);
  84. CeErpTradeCell.UpdateRelationOrder(ctid);
  85. }
  86. catch (Exception ex)
  87. {
  88. //errorFileLst.Add("'" + dr["ctid"].ToString() + "'");
  89. XLog.SaveLog(0, "下载发生错误,ctid:" + ctid + "," + ex.Message);
  90. }
  91. }
  92. private void downloadcayingtonge()
  93. {
  94. string tids = Request["hexdata"];
  95. int onlyDownFile = 0;//只下文件
  96. if (Request["onlyfile"] != null)
  97. {
  98. Int32.TryParse(Request["onlyfile"], out onlyDownFile);
  99. }
  100. int cyt = 0;
  101. if (Request["cyt"] != null)
  102. {
  103. Int32.TryParse(Request["cyt"], out cyt);
  104. }
  105. int userId = 0;
  106. if (Request["userid"] != null)
  107. {
  108. Int32.TryParse(Request["userid"], out userId);
  109. }
  110. String ui = "";
  111. if (cyt == 1)
  112. {
  113. StringBuilder sql = new StringBuilder();
  114. sql.AppendFormat("select ctid,seller_memo,FinishDesignTime,OrderState,SupplierName,FileMd5,IsSF from view_erptradecell where FinishDesignTime is not null and ctid in ({0}) {1}", ("'" + tids.Replace(",", "','") + "'"), ((onlyDownFile == 1) ? "" : " and OrderState=5 "));
  115. DataTable dt = CeErpTradeCell.ExecuteDataset(sql.ToString()).Tables[0];
  116. if (dt == null || dt.Rows.Count < 1)
  117. {
  118. conErc("没有找到相关订单");
  119. return;
  120. }
  121. List<string> files = new List<string>();
  122. List<string> noFileLst = new List<string>();
  123. List<string> ctidLst = new List<string>();
  124. foreach (DataRow dr in dt.Rows)
  125. {
  126. string fileMd5 = "", fileNames = "";
  127. String seller_memo = "";
  128. int ISSF = 0;
  129. string finishDesignTime = getDesignTime(dr["FinishDesignTime"]);
  130. string df_name = upPath + "\\" + finishDesignTime + "\\" + formatMemo(dr["seller_memo"]);
  131. if (!Convert.IsDBNull(dr["seller_memo"]))
  132. {
  133. seller_memo = dr["seller_memo"].ToString();
  134. }
  135. if (!Convert.IsDBNull(dr["IsSF"]))
  136. {
  137. ISSF = Convert.ToInt32(dr["IsSF"] == null ? 0 : dr["IsSF"]);
  138. }
  139. string fname = getCanDownFile(df_name);
  140. if (string.IsNullOrEmpty(fname))
  141. {
  142. noFileLst.Add("'" + dr["ctid"].ToString() + "'");
  143. ui += dr["ctid"].ToString() + "未找到附件,";
  144. continue;
  145. }
  146. files.Add(fname);
  147. ctidLst.Add(dr["ctid"].ToString());
  148. fileMd5 += "," + dr["FileMd5"].ToString();
  149. fileNames += Path.GetFileName(fname);
  150. String er = downLoadFiles(userId, dr["ctid"].ToString(), fname, fileNames, seller_memo, ISSF);
  151. if (er.Contains("成功"))
  152. {
  153. copyFile(getDesignDate(dr["FinishDesignTime"]), dr["SupplierName"].ToString(), fname);
  154. }
  155. ui += er + ",";
  156. }
  157. conSuc(ui);
  158. }
  159. else
  160. {
  161. conSuc(ui);
  162. }
  163. }
  164. private void downloadMore()
  165. {
  166. if (Request["hexdata"] == null || Request["hexdata"].Trim() == "")
  167. {
  168. conErc("错误的下载访问");
  169. return;
  170. }
  171. string tids = Request["hexdata"];
  172. int onlyDownFile = 0;//只下文件
  173. if (Request["onlyfile"] != null)
  174. {
  175. Int32.TryParse(Request["onlyfile"], out onlyDownFile);
  176. }
  177. int cyt = 0;
  178. if (Request["cyt"] != null)
  179. {
  180. Int32.TryParse(Request["cyt"], out cyt);
  181. }
  182. int userId = 0;
  183. if (Request["userid"] != null)
  184. {
  185. Int32.TryParse(Request["userid"], out userId);
  186. }
  187. int mvClientDown = 0;//转移到客户端下载
  188. int isFromClient = 0;
  189. if (onlyDownFile != 1)
  190. {
  191. if (Request["supplier"] == null || Request["supplier"].ToString() != "1")//如果不是只下文件,那他就要是供应商
  192. {
  193. conErc("错误的下载访问");
  194. return;
  195. }
  196. else
  197. {
  198. Int32.TryParse(Request["isFromClient"], out isFromClient);
  199. if (userId > 0 && isFromClient != 1)
  200. {
  201. string file_client_down_flg = erpRedis.RedisHelper.StringGet("file_client_down_flg_" + userId);
  202. if (file_client_down_flg != null && file_client_down_flg == "1")
  203. {
  204. mvClientDown = 1;
  205. }
  206. }
  207. }
  208. }
  209. try
  210. {
  211. StringBuilder sql = new StringBuilder();
  212. sql.AppendFormat("select ctid,seller_memo,FinishDesignTime,OrderState,SupplierName,FileMd5,IsSF from view_erptradecell where FinishDesignTime is not null and ctid in ({0}) {1}", ("'" + tids.Replace(",", "','") + "'"), ((onlyDownFile == 1 || isFromClient == 1) ? "" : " and OrderState=5 "));
  213. DataTable dt = CeErpTradeCell.ExecuteDataset(sql.ToString()).Tables[0];
  214. if (dt == null || dt.Rows.Count < 1)
  215. {
  216. conErc("没有找到相关订单");
  217. return;
  218. }
  219. string fileMd5 = "", fileNames = "";
  220. String seller_memo = "";
  221. int ISSF = 0;
  222. List<string> files = new List<string>();
  223. List<string> noFileLst = new List<string>();
  224. List<string> ctidLst = new List<string>();
  225. foreach (DataRow dr in dt.Rows)
  226. {
  227. string finishDesignTime = getDesignDate(dr["FinishDesignTime"]);
  228. string df_name = upPath + "\\" + finishDesignTime + "\\" + formatMemo(dr["seller_memo"]);
  229. if (!Convert.IsDBNull(dr["seller_memo"]))
  230. {
  231. seller_memo = dr["seller_memo"].ToString();
  232. }
  233. if (!Convert.IsDBNull(dr["IsSF"]))
  234. {
  235. ISSF = Convert.ToInt32(dr["IsSF"] == null ? 0 : dr["IsSF"]);
  236. }
  237. string fname = getCanDownFile(df_name);
  238. if (string.IsNullOrEmpty(fname))
  239. {
  240. noFileLst.Add("'" + dr["ctid"].ToString() + "'");
  241. continue;
  242. }
  243. files.Add(fname);
  244. ctidLst.Add(dr["ctid"].ToString());
  245. fileMd5 += "," + dr["FileMd5"].ToString();
  246. fileNames += "#$#" + Path.GetFileName(fname);
  247. if (onlyDownFile != 1 && mvClientDown != 1)
  248. copyFile(getDesignDate(dr["FinishDesignTime"]), dr["SupplierName"].ToString(), fname);
  249. }
  250. if (files.Count == 0)
  251. {
  252. conErc("没有找到相关的设计附件");
  253. return;
  254. }
  255. if (noFileLst.Count > 0)
  256. {
  257. string tips = "";
  258. string notids = string.Join(",", noFileLst.ToArray());
  259. sql = new StringBuilder();
  260. sql.AppendFormat("insert into CE_ErpTradeLog(tid,orderstate,userid,operatetime,con) select ctid,{1},{2},getdate(),'{3}' from ce_erptradecell where ctid in ({0}) ;", notids, (int)OrderState.下单完成, 0, "找不到设计文件");
  261. CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  262. tips += "找不到文件,单号:" + notids;
  263. conErc(tips);
  264. return;
  265. }
  266. if (mvClientDown == 1)
  267. {
  268. for (int i = 0; i < files.Count; i++)
  269. {
  270. if (onlyDownFile != 1)
  271. updateIsDownSuccess(userId, ctidLst[i]);
  272. }
  273. string key = "file_client_down_list_" + userId;
  274. string data = "{\"hexdata\":\"" + tids + "\",\"fileMd5\":\"" + fileMd5.Substring(1) + "\",\"supplier\":\""
  275. + (Request["supplier"] != null ? Request["supplier"].ToString() : "0") + "\",\"fileName\":\"" + System.Web.HttpUtility.UrlEncode(fileNames, System.Text.Encoding.GetEncoding("GB2312")) + "\"}";
  276. erpRedis.RedisHelper.ListLeftPush(key, data);
  277. return;
  278. }
  279. if (files.Count == 1)
  280. {
  281. downLoadFile(userId, ctidLst[0], files[0], onlyDownFile, isFromClient);
  282. if (cyt == 1)
  283. {
  284. downLoadFiles(userId, ctidLst[0], files[0], fileNames, seller_memo, ISSF);
  285. }
  286. }
  287. else
  288. {
  289. ZipFileDownload(userId, ctidLst, files, "LT_" + DateTime.Now.ToString("yyyyMMddhhMmss") + ".zip", onlyDownFile, isFromClient); //downLoadFile(userId, ctidLst[i], files[i]);
  290. }
  291. //conSuc("文件已下载完成");
  292. return;
  293. }
  294. catch (Exception ex)
  295. {
  296. conErc("错误的下载访问" + ex.Message);
  297. return;
  298. }
  299. }
  300. private string formatMemo(object memo)
  301. {
  302. string m = memo.ToString();
  303. m = m.Replace("\\", "").Replace("/", "").Replace(":", "").Replace("*", "").Replace("?", "").Replace("<", "").Replace(">", "").Replace("|", "");
  304. return m;
  305. }
  306. private void copyFile(string date, string supplier, string file)
  307. {
  308. string path = copyPath + "\\" + date + "\\" + supplier + "\\" + "车间下载";
  309. if (!Directory.Exists(path)) Directory.CreateDirectory(path);
  310. string fname = Path.GetFileName(file);
  311. File.Copy(file, path + "\\" + fname, true);
  312. if (!File.Exists(path + "\\" + fname))
  313. {
  314. File.Copy(file, path + "\\" + fname, true);
  315. }
  316. }
  317. private string getDesignTime(object v)
  318. {
  319. if (v.ToString() == "") return "";
  320. return Convert.ToDateTime(v).ToString("yyyyMMdd");
  321. }
  322. private string getDesignDate(object v)
  323. {
  324. return DateTime.Now.ToString("yyyy-MM-dd");
  325. /*if (v.ToString() == "") return "";
  326. return Convert.ToDateTime(v).ToString("yyyy-MM-dd");*/
  327. }
  328. /// 批量进行多个文件压缩到一个文件
  329. /// </summary>
  330. /// <param name="files">文件列表(绝对路径)</param> 这里用的数组,你可以用list 等或者
  331. /// <param name="zipFileName">生成的zip文件名称</param>
  332. private void ZipFileDownload(int userId, List<string> ctidLst, List<string> files, string zipFileName, int onlyDownFile, int isFromClient)
  333. {
  334. MemoryStream ms = new MemoryStream();
  335. byte[] buffer = null;
  336. using (ZipFile file = ZipFile.Create(ms))
  337. {
  338. file.BeginUpdate();
  339. //file.NameTransform = new ZipNameTransform();
  340. file.NameTransform = new MyNameTransfom();
  341. foreach (var item in files)
  342. {
  343. if (File.Exists(item)) file.Add(item);
  344. }
  345. file.CommitUpdate();
  346. buffer = new byte[ms.Length];
  347. ms.Position = 0;
  348. ms.Read(buffer, 0, buffer.Length); //读取文件内容(1次读ms.Length/1024M)
  349. ms.Flush();
  350. ms.Close();
  351. }
  352. Response.Clear();
  353. Response.Buffer = true;
  354. Response.ContentType = "application/x-zip-compressed";
  355. Response.AddHeader("Set-Cookie", "fileDownload=true; path=/");
  356. Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(zipFileName));
  357. Response.BinaryWrite(buffer);
  358. Page.Response.Flush();
  359. for (int i = 0; i < files.Count; i++)
  360. {
  361. if (onlyDownFile != 1 && isFromClient != 1)
  362. updateIsDownSuccess(userId, ctidLst[i]);
  363. XLog.SaveLog(userId, files[i] + " is success");
  364. }
  365. }
  366. //public static object downfileObj = new object();
  367. private void downLoadFile(int userId, string ctid, string file, int onlyDownFile, int isFromClient)
  368. {
  369. XLog.SaveLog(userId, file);
  370. string filePath = file;
  371. string dfile = Path.GetFileName(file);
  372. FileStream fs = new FileStream(filePath, FileMode.Open);
  373. byte[] bytes = new byte[(int)fs.Length];
  374. fs.Read(bytes, 0, bytes.Length);
  375. fs.Close();
  376. Response.Clear();
  377. //
  378. Response.ClearContent();
  379. Response.ClearHeaders();
  380. Response.ContentType = "application/octet-stream";
  381. //通知浏览器下载文件而不是打开\\fileDownload=true; path=/
  382. Response.AddHeader("Set-Cookie", "fileDownload=true; path=/;");
  383. //Response.AddHeader("Cache-Control", "no-cache, no-store, must-revalidate");
  384. Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(dfile, System.Text.Encoding.UTF8));
  385. Response.AddHeader("Content-Length", bytes.Length.ToString());
  386. Response.BinaryWrite(bytes);
  387. Response.Flush();
  388. if (onlyDownFile != 1 && isFromClient != 1)
  389. updateIsDownSuccess(userId, ctid);
  390. XLog.SaveLog(userId, file + " is success");
  391. }
  392. private String downLoadFiles(int userId, string ctid, string file, String fileNames, String seller_memo, int ISSF)
  393. {
  394. int IsFileEncrypt = IsFileEncrypted(file);
  395. if (IsFileEncrypt == 1 && File.Exists(file))
  396. {
  397. string key = "gBQnlxiBb7MthH9644V0W0pFwqYZgyy7";
  398. var sb = new StringBuilder(key);
  399. //Linux系统的接口要调用一次,Windows系统要调用两次
  400. CreateUserKey(sb, key.Length);
  401. CreateUserKey(sb, key.Length); //破解用dse生成的文件,需要调2次。
  402. int result = InitAesKey(sb, sb.Length);
  403. result = IsInitedAesKey();
  404. if (result != 1)
  405. {
  406. addLog(ctid, userId, "初始化秘钥失败" + result, 0);
  407. return ctid + "调用失败";
  408. }
  409. uint a = DecFile(file);
  410. if (a != 0)
  411. {
  412. addLog(ctid, userId, "解密失败" + a, 0);
  413. return ctid + "调用失败";
  414. }
  415. }
  416. int Isshunfen = 2;
  417. int Isjifu = 1;
  418. if (ISSF > 0)
  419. {
  420. Isshunfen = 1;
  421. }
  422. if (ISSF == 2)
  423. {
  424. Isjifu = 0;
  425. }
  426. UpLoadFile uf = new UpLoadFile();
  427. string YEAR = DateTime.Now.Year.ToString();
  428. string MONTH = DateTime.Now.Month.ToString();
  429. string DAY = DateTime.Now.Day.ToString();
  430. string strid = Guid.NewGuid().ToString("N");
  431. string fileExtension = Path.GetExtension(fileNames);//文件格式
  432. string finalfilename = strid + Path.GetExtension(fileNames);// ".cdr";
  433. string onlinepathfilename = "Uploads/temp/" + YEAR + "-" + MONTH + "-" + DAY + "/" + finalfilename;
  434. uf.uploadFilName(file, onlinepathfilename);
  435. string output = fileExtension.Replace(".", ""); // 移除点(.)
  436. CeErpTradeCell ce = new CeErpTradeCell();
  437. ce = CeErpTradeCell.GetByCtid(ctid);
  438. if (ce.ReturnReason != "")//打回先取消
  439. {
  440. try
  441. {
  442. cancelOrder(ctid);
  443. }
  444. catch (Exception ex)
  445. {
  446. addLog(ctid, userId, "订单取消失败" + ex.ToString(), 0);
  447. }
  448. }
  449. if (ce.OrderState == 5)
  450. {
  451. JObject jsonObject = new JObject
  452. {
  453. { "Userid", "77886" },
  454. { "pwd", "lt666888" },
  455. { "FileId", strid },
  456. { "ext", output },
  457. { "platformorder", ce.tid },//淘宝单号
  458. { "Filename", fileNames },
  459. { "Isshunfen", Isshunfen },
  460. { "Isjifu", Isjifu },
  461. { "LTOrderId", ce.ctid }
  462. };
  463. string response = HttpPost("http://www.kiy.cn/m-mobile/autobaojia/LTInsertNewOrder", jsonObject.ToString());
  464. JObject jsonObjects = JObject.Parse(response);
  465. string msg = (string)jsonObjects["msg"];
  466. if (msg == "插入订单成功")
  467. {
  468. string sql_pay = "INSERT INTO CE_CaiYingTongLog (ctid, ctime,type,msg) VALUES ('" + ctid + "', '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'," + 0 + ",'" + msg + "');";
  469. CeErpTradeCell.ExecuteNonQuery(sql_pay.ToString());
  470. addLog(ctid, userId, "上传彩印通接口成功:" + msg, ce.OrderState);
  471. if (ce != null)
  472. {
  473. ce.FinishPlaceTime = DateTime.Now;
  474. ce.OrderState = 6;
  475. ce.IsReturn = 0;
  476. ce.PlaceUserId = userId;
  477. ce.Update();
  478. CeErpTradeLog logenty = new CeErpTradeLog();
  479. logenty.tid = ctid;
  480. logenty.OrderState = 6;
  481. logenty.UserId = userId;
  482. logenty.OperateTime = DateTime.Now;
  483. logenty.Con = "下载设计文件";
  484. logenty.Create();
  485. }
  486. return ctid + "上传成功";
  487. }
  488. else
  489. {
  490. string sql_pay = "INSERT INTO CE_CaiYingTongLog (ctid, ctime,type,msg) VALUES ('" + ctid + "', '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'," + 1 + ",'" + msg + "');";
  491. CeErpTradeCell.ExecuteNonQuery(sql_pay.ToString());
  492. addLog(ctid, userId, "上传彩印通接口失败:" + msg, ce.OrderState);
  493. XLog.SaveLog(userId, ctid + "订单下单接口调用失败!" + msg);
  494. return ctid + "调用失败";
  495. }
  496. }
  497. return ctid + "调用失败";
  498. }
  499. public static void cancelOrder(string ctid)
  500. {
  501. JObject jsonObject = new JObject
  502. {
  503. { "Userid", "77886" },
  504. { "pwd", "lt666888" },
  505. { "LTOrderId", ctid }
  506. };
  507. string response = HttpPost("http://www.kiy.cn/m-mobile/autobaojia/LTCancelOrder", jsonObject.ToString());
  508. }
  509. public static void addLog(string ctid, int userid, string con, int orderState = 0, int aftersaleState = 0)
  510. {
  511. CeErpTradeLog log = new CeErpTradeLog();
  512. log.tid = ctid;
  513. log.UserId = userid;
  514. log.Con = con;
  515. log.OrderState = orderState;
  516. log.AfterSaleState = aftersaleState;
  517. log.OperateTime = DateTime.Now;
  518. log.Create();
  519. }
  520. public static string HttpPost(string url, string param = null)
  521. {
  522. HttpWebRequest request;
  523. //如果是发送HTTPS请求
  524. if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  525. {
  526. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
  527. request = WebRequest.Create(url) as HttpWebRequest;
  528. request.ProtocolVersion = HttpVersion.Version10;
  529. }
  530. else
  531. {
  532. request = WebRequest.Create(url) as HttpWebRequest;
  533. }
  534. request.Method = "POST";
  535. request.ContentType = "application/json";
  536. request.Accept = "*/*";
  537. request.Timeout = 120000;
  538. request.AllowAutoRedirect = false;
  539. StreamWriter requestStream = null;
  540. WebResponse response = null;
  541. string responseStr = null;
  542. try
  543. {
  544. requestStream = new StreamWriter(request.GetRequestStream());
  545. requestStream.Write(param);
  546. requestStream.Close();
  547. response = request.GetResponse();
  548. if (response != null)
  549. {
  550. StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  551. responseStr = reader.ReadToEnd();
  552. reader.Close();
  553. }
  554. }
  555. catch (Exception ex)
  556. {
  557. return ex.Message;
  558. }
  559. finally
  560. {
  561. request = null;
  562. requestStream = null;
  563. response = null;
  564. }
  565. return responseStr;
  566. }
  567. private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
  568. {
  569. return true; //总是接受
  570. }
  571. }