This repository was archived by the owner on Sep 4, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathXJHTTP.cs
More file actions
1733 lines (1649 loc) · 63.3 KB
/
Copy pathXJHTTP.cs
File metadata and controls
1733 lines (1649 loc) · 63.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace HttpCode.Core
{
/// <summary>
/// WinInet的方式请求数据
/// </summary>
public class Wininet
{
#region 字段/属性
/// <summary>
/// 默认UserAgent
/// </summary>
public string UserAgent = "Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1; 125LA; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";
private int _WininetTimeOut = 0;
/// <summary>
/// Wininet超时时间 默认0 不设置超时,由于是自行实现(微软没修复超时的bug) 所以如果设置后,每次请求都会暂停.
/// </summary>
public int WininetTimeOut
{
get { return _WininetTimeOut; }
set { _WininetTimeOut = value; }
}
#endregion
/// <summary>
/// 自动解析编码
/// </summary>
/// <param name="ms">结果流</param>
/// <returns>异常时返回null</returns>
private string EncodingPack(MemoryStream ms)
{
Match meta = Regex.Match(Encoding.Default.GetString(ms.ToArray()), "<meta([^<]*)charset=([^<]*)[\"']", RegexOptions.IgnoreCase);
string c = (meta.Groups.Count > 1) ? meta.Groups[2].Value.ToUpper().Trim() : string.Empty;
if (c.IndexOf("\"") > 0)
{
c = c.Split('\"')[0];
}
if (c.Length > 2)
{
if (c.IndexOf("UTF-8") != -1)
{
return Encoding.GetEncoding("UTF-8").GetString(ms.ToArray());
}
}
return Encoding.GetEncoding("GBK").GetString(ms.ToArray());
}
/// <summary>
/// 将内存流转换为字符串
/// </summary>
/// <param name="mstream">需要转换的流</param>
/// <returns></returns>
public string GetDataPro(MemoryStream mstream)
{
using (MemoryStream ms = mstream)
{
if (ms != null)
{
//无视编码
return EncodingPack(ms);
}
else
{
return null;
}
}
}
/// <summary>
/// 获取网页图片(Image)
/// </summary>
/// <param name="mstream">Stream流</param>
/// <returns></returns>
public Image GetImage(MemoryStream mstream)
{
using (MemoryStream ms = mstream)
{
if (ms == null)
{
return null;
}
Image img = Image.FromStream(ms);
return img;
}
}
#region Cookie操作方法
/// <summary>
/// 遍历CookieContainer 转换为Cookie集合对象
/// </summary>
/// <param name="cc"></param>
/// <returns>Cookie集合对象</returns>
public List<Cookie> GetAllCookies(CookieContainer cc)
{
List<Cookie> lstCookies = new List<Cookie>();
Hashtable table = (Hashtable)cc.GetType().InvokeMember("m_domainTable",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField |
System.Reflection.BindingFlags.Instance, null, cc, new object[] { });
foreach (object pathList in table.Values)
{
SortedList lstCookieCol = (SortedList)pathList.GetType().InvokeMember("m_list",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField
| System.Reflection.BindingFlags.Instance, null, pathList, new object[] { });
foreach (CookieCollection colCookies in lstCookieCol.Values)
foreach (Cookie c in colCookies) lstCookies.Add(c);
}
return lstCookies;
}
/// <summary>
/// 将String转CookieContainer
/// </summary>
/// <param name="Domain">Cookie对应的Domain</param>
/// <param name="cookie">具体值</param>
/// <returns>转换后的Container对象</returns>
public CookieContainer StringToCookie(string Domain, string cookie)
{
string[] arrCookie = cookie.Split(';');
CookieContainer cookie_container = new CookieContainer(); //加载Cookie
foreach (string sCookie in arrCookie)
{
if (!string.IsNullOrEmpty(sCookie))
{
Cookie ck = new Cookie();
ck.Name = sCookie.Split('=')[0].Trim();
ck.Value = sCookie.Split('=')[1].Trim();
ck.Domain = Domain;
try
{
cookie_container.Add(ck);
}
catch
{
continue;
}
}
}
return cookie_container;
}
/// <summary>
/// 将CookieContainer转换为string类型
/// </summary>
/// <param name="cc">需要转换的Container对象</param>
/// <returns>字符串结果</returns>
public string CookieToString(CookieContainer cc)
{
System.Collections.Generic.List<Cookie> lstCookies = new System.Collections.Generic.List<Cookie>();
Hashtable table = (Hashtable)cc.GetType().InvokeMember("m_domainTable",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField |
System.Reflection.BindingFlags.Instance, null, cc, new object[] { });
StringBuilder sb = new StringBuilder();
foreach (object pathList in table.Values)
{
SortedList lstCookieCol = (SortedList)pathList.GetType().InvokeMember("m_list",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField
| System.Reflection.BindingFlags.Instance, null, pathList, new object[] { });
foreach (CookieCollection colCookies in lstCookieCol.Values)
foreach (Cookie c in colCookies)
{
sb.Append(c.Name).Append("=").Append(c.Value).Append(";");
}
}
return sb.ToString();
}
#endregion
}
/// <summary>
/// 系统时间结构体
/// </summary>
public struct SystemTime
{
/// <summary>
/// 年
/// </summary>
public ushort wYear;
/// <summary>
/// 月
/// </summary>
public ushort wMonth;
/// <summary>
/// 周
/// </summary>
public ushort wDayOfWeek;
/// <summary>
/// 日
/// </summary>
public ushort wDay;
/// <summary>
/// 时
/// </summary>
public ushort wHour;
/// <summary>
/// 分
/// </summary>
public ushort wMinute;
/// <summary>
/// 秒
/// </summary>
public ushort wSecond;
/// <summary>
/// 毫秒
/// </summary>
public ushort wMiliseconds;
}
/// <summary>
/// 玄机网一键HTTP类库
/// 懒人库/快捷库
/// </summary>
public class XJHTTP
{
HttpItems item = new HttpItems();
HttpHelpers http = new HttpHelpers();
Wininet wnet = new Wininet();
HttpResults hr;
#region Json序列化方法 Framework 2.0下无效 ,默认注释.如需启用 请参考类库文首提示
/*
/// <summary>
/// 将指定的Json字符串转为指定的T类型对象
/// </summary>
/// <param name="jsonstr">字符串</param>
/// <returns>转换后的对象,失败为Null</returns>
public object JsonToObject<T>(string jsonstr)
{
try
{
JavaScriptSerializer jss = new JavaScriptSerializer();
return jss.Deserialize<T>(jsonstr);
}
catch (Exception)
{
return null;
}
}
/// <summary>
/// 将指定的对象转为Json字符串
/// </summary>
/// <param name="obj">对象</param>
/// <returns>转换后的字符串失败为空字符串</returns>
public string ObjectToJson(object obj)
{
try
{
JavaScriptSerializer jss = new JavaScriptSerializer();
return jss.Serialize(obj);
}
catch (Exception)
{
return string.Empty;
}
}*/
#endregion
#region 设置/获取系统时间 / 获取当前/指定日期时间戳方法 / GMT时间与本地时间互转
/// <summary>
/// 时间戳转为C#格式时间
/// </summary>
/// <param name="timeStamp">Unix时间戳格式</param>
/// <returns>C#格式时间</returns>
public DateTime GetTime(string timeStamp)
{
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
long lTime = long.Parse(timeStamp + "0000");
TimeSpan toNow = new TimeSpan(lTime);
return dtStart.Add(toNow);
}
/// <summary>
/// 获取JS时间戳 13位(反射 性能较差如果在乎性能,请考虑GetTimeByCSharp13 方法)
/// </summary>
/// <returns></returns>
public string GetTimeByJs()
{
Type obj = Type.GetTypeFromProgID("ScriptControl");
if (obj == null) return null;
object ScriptControl = Activator.CreateInstance(obj);
obj.InvokeMember("Language", BindingFlags.SetProperty, null, ScriptControl, new object[] { "JScript" });
string js = "function time(){return new Date().getTime()}";
obj.InvokeMember("AddCode", BindingFlags.InvokeMethod, null, ScriptControl, new object[] { js });
return obj.InvokeMember("Eval", BindingFlags.InvokeMethod, null, ScriptControl, new object[] { "time()" }).ToString();
}
/// <summary>
/// 返回13位时间戳 非JS方式
/// </summary>
/// <param name="nAddSecond"></param>
/// <returns></returns>
public string GetTimeByCSharp13(int nAddSecond = 0)
{
return (DateTime.UtcNow.AddSeconds(nAddSecond) - DateTime.Parse("1970-01-01 0:0:0")).TotalMilliseconds.ToString("0");
}
/// <summary>
/// 获取时间戳 C# 10位
/// </summary>
/// <returns></returns>
public string GetTimeByCSharp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalSeconds).ToString();
}
/// <summary>
/// 指定时间转换时间戳
/// </summary>
/// <param name="time"></param>
/// <returns></returns>
public string GetTimeToStamp(DateTime time)
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
return ((time - startTime).TotalSeconds).ToString();
}
/// <summary>
/// 获取服务器返回的时间,如果Header中没有Date则返回当前时间
/// </summary>
/// <param name="hrs">请求结果对象</param>
/// <returns>返回本地时区Datatime数据</returns>
public DateTime GetServerTime(HttpResults hrs)
{
try
{
return GetTime4Gmt(hrs.Header["Date"].ToString());
}
catch
{
return DateTime.Now;
}
}
/// <summary>
/// 本地时间转成GMT时间 (参数如果不传入则为当前时间)
/// 本地时间为:2011-9-29 15:04:39
/// 转换后的时间为:Thu, 29 Sep 2011 07:04:39 GMT
/// </summary>
/// <param name="dt">参数如果不传入则为当前时间 DateTime.Now</param>
/// <returns></returns>
public string GetTimeToGMTString(DateTime dt = default(DateTime))
{
if (dt == default(DateTime))
{
dt = DateTime.Now;
}
return dt.ToUniversalTime().ToString("r");
}
/// <summary>
///本地时间转成GMT格式的时间(参数如果不传入则为当前时间)
///本地时间为:2011-9-29 15:04:39
///转换后的时间为:Thu, 29 Sep 2011 15:04:39 GMT+0800
/// </summary>
/// <param name="dt">参数如果不传入则为当前时间 DateTime.Now</param>
/// <returns></returns>
public string GetTimeToGMTFormat(DateTime dt = default(DateTime))
{
if (dt == default(DateTime))
{
dt = DateTime.Now;
}
return dt.ToString("r") + dt.ToString("zzz").Replace(":", "");
}
/// <summary>
/// GMT时间转成本地时间
/// DateTime dt1 = GMT2Local("Thu, 29 Sep 2011 07:04:39 GMT");
/// 转换后的dt1为:2011-9-29 15:04:39
/// DateTime dt2 = GMT2Local("Thu, 29 Sep 2011 15:04:39 GMT+0800");
/// 转换后的dt2为:2011-9-29 15:04:39
/// </summary>
/// <param name="gmt">字符串形式的GMT时间</param>
/// <returns></returns>
public DateTime GetTime4Gmt(string gmt)
{
DateTime dt = DateTime.MinValue;
try
{
string pattern = "";
if (gmt.IndexOf("+0") != -1)
{
gmt = gmt.Replace("GMT", "");
pattern = "ddd, dd MMM yyyy HH':'mm':'ss zzz";
}
if (gmt.ToUpper().IndexOf("GMT") != -1)
{
pattern = "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'";
}
if (pattern != "")
{
dt = DateTime.ParseExact(gmt, pattern, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal);
dt = dt.ToLocalTime();
}
else
{
dt = Convert.ToDateTime(gmt);
}
}
catch
{
}
return dt;
}
#endregion
#region 字符串处理方法
/// <summary>
/// 取文本中间
/// </summary>
/// <param name="allStr">原字符</param>
/// <param name="firstStr">前面的文本</param>
/// <param name="lastStr">后面的文本</param>
/// <returns>返回获取的值</returns>
public string GetStringMid(string allStr, string firstStr, string lastStr)
{
//取出前面的位置
int index1 = allStr.IndexOf(firstStr);
//取出后面的位置
int index2 = allStr.IndexOf(lastStr, index1 + firstStr.Length);
if (index1 < 0 || index2 < 0)
{
return "";
}
//定位到前面的位置
index1 = index1 + firstStr.Length;
//判断要取的文本的长度
index2 = index2 - index1;
if (index1 < 0 || index2 < 0)
{
return "";
}
//取出文本
return allStr.Substring(index1, index2);
}
/// <summary>
/// 批量取文本中间
/// </summary>
/// <param name="allStr">原字符</param>
/// <param name="firstStr">前面的文本</param>
/// <param name="lastStr">后面的文本</param>
/// <param name="regexCode">默认为万能表达式(.*?)</param>
/// <returns>返回结果集合</returns>
public List<string> GetStringMids(string allStr, string firstStr, string lastStr, string regexCode = "(.*?)")
{
List<string> list = new List<string>();
string reString = string.Format("{0}{1}{2}", firstStr, regexCode, lastStr);
Regex reg = new Regex(reString);
MatchCollection mc = reg.Matches(allStr);
for (int i = 0; i < mc.Count; i++)
{
GroupCollection gc = mc[i].Groups; //得到所有分组
for (int j = 1; j < gc.Count; j++) //多分组
{
string temp = gc[j].Value;
if (!string.IsNullOrEmpty(temp))
{
list.Add(temp);
}
}
}
return list;
}
/// <summary>
/// URL加密适用于淘宝中文编码算法
/// </summary>
/// <param name="str">明文</param>
/// <returns>密文</returns>
public string EnUrlMethod(string str)
{
byte[] buff = Encoding.Default.GetBytes(str);
string s = "";
for (int ix = 0; ix < buff.Length; ix++)
{
s += "%" + buff[ix].ToString("x2");
}
s = s.ToUpper(); //%62%62%73%2E%6D%73%64%6E%35%2E%63%6F%6D%D0%FE%BB%FA%C2%DB%CC%B3%B3%F6%C6%B7
return s;
}
/// <summary>
/// Url编码,encoding默认为utf8编码
/// </summary>
/// <param name="str">需要编码的字符串</param>
/// <param name="encoding">指定编码类型</param>
/// <returns>编码后的字符串</returns>
public string UrlEncoding(string str, Encoding encoding = null)
{
if (encoding == null)
{
return System.Web.HttpUtility.UrlEncode(str, Encoding.UTF8);
}
else
{
return System.Web.HttpUtility.UrlEncode(str, encoding);
}
}
/// <summary>
/// URL解密适用于淘宝中文编码算法
/// </summary>
/// <param name="str">密文</param>
/// <returns>明文</returns>
public string DeUrlMethod(string str)
{
try
{
//改进后更适合的算法
List<byte> li2 = new List<byte>();
string[] strs = str.Split('%');
for (int j = 0; j < strs.Length; j++)
{
if (!string.IsNullOrEmpty(strs[j]))
{
li2.Add(Convert.ToByte(strs[j], 16));
}
}
string res = Encoding.Default.GetString(li2.ToArray());//bbs.msdn5.com玄机论坛出品
return res;
}
catch
{
return "Error";
}
}
/// <summary>
/// Url解码,encoding默认为utf8编码
/// </summary>
/// <param name="str">需要解码的字符串</param>
/// <param name="encoding">指定解码类型</param>
/// <returns>解码后的字符串</returns>
public string UrlDecoding(string str, Encoding encoding = null)
{
if (encoding == null)
{
return System.Web.HttpUtility.UrlDecode(str, Encoding.UTF8);
}
else
{
return System.Web.HttpUtility.UrlDecode(str, encoding);
}
}
/// <summary>
/// Html解码
/// </summary>
/// <param name="str">需要解码的字符</param>
/// <returns></returns>
public string HtmlDecode(string str)
{
string[] strsx = str.Split('△');
if (strsx.Length > 1)
{
return FromUnicodeString(strsx[0], strsx[1].Trim());//Decode2Html(strsx[0], strsx[1].Trim());
}
else
{
return Decode2Html(str);
}
}
/// <summary>
/// 解析任意符号开头的编码后续数据符合Hex编码
/// </summary>
/// <param name="param"></param>
/// <param name="sp"></param>
/// <returns></returns>
private string Decode2Html(string param, string sp = "&#")
{
string[] paramstr = param.Replace(sp, sp + " ").Replace(sp, "").Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
string str = string.Empty;
foreach (string item in paramstr)
{
try
{
str += (char)int.Parse(item, System.Globalization.NumberStyles.HexNumber);
}
catch
{
str += item;
continue;
}
}
// 如果失败请尝试这种办法 可解决变异HTML 开头非&# :-> StringWriter myWriter = new StringWriter(); System.Web.HttpUtility.HtmlDecode(param,myWriter); return myWriter.ToString();
return str;
}
/// <summary>
/// Html编码
/// </summary>
/// <param name="param">需要编码的字符</param>
/// <returns>返回编码后数据</returns>
public string HtmlEncode(string param)
{
string str = string.Empty;
foreach (char item in param.ToCharArray())
{
try
{
str += "&#" + Convert.ToInt32(item).ToString("x4") + " ";
}
catch
{
str += "ToHtml Error";
}
}
return str;
}
/// <summary>
/// 取文本右边
/// 默认取出右边所有文本,如果需要取固定长度请设置 length参数
/// 异常则返回空字符串
/// </summary>
/// <param name="str">原始字符串</param>
/// <param name="right">需要确认位置的字符串</param>
/// <param name="length">默认0,如果设置按照设置的值取出数据</param>
/// <returns>返回结果</returns>
public string Right(string str, string right, int length = 0)
{
int pos = str.IndexOf(right, StringComparison.Ordinal);
if (pos < 0) return "";
int len = str.Length;
if (len - pos - right.Length <= 0) return "";
string result = "";
if (length == 0)
{
result = str.Substring(pos + right.Length, len - (pos + right.Length));
}
else
{
result = str.Substring(pos + right.Length, length);
}
return result;
}
/// <summary>
/// 取文本左边
/// 默认取出左边所有文本,如果需要取固定长度请设置 length参数
/// 异常则返回空字符串
/// </summary>
/// <param name="str">原始字符串</param>
/// <param name="left">需要确认位置的字符串</param>
/// <param name="length">默认0,如果设置按照设置的值取出数据</param>
/// <returns>返回结果</returns>
public string Left(string str, string left, int length = 0)
{
var pos = str.IndexOf(left, StringComparison.Ordinal);
if (pos < 0) return "";
string result = "";
if (length == 0)
{
result = str.Substring(0, pos);
}
else
{
result = str.Substring(length, pos);
}
return result;
}
/// <summary>
/// 取文本中间 正则方式
/// </summary>
/// <param name="html">原始Html</param>
/// <param name="s">开始字符串</param>
/// <param name="e">结束字符串</param>
/// <returns>返回获取结果</returns>
public string GetMidHtml(string html, string s, string e)
{
string rx = string.Format("{0}{1}{2}", s, RegexString.AllHtml, e);
if (Regex.IsMatch(html, rx, RegexOptions.IgnoreCase))
{
Match match = Regex.Match(html, rx, RegexOptions.IgnoreCase);
if (match != null && match.Groups.Count > 0)
{
return match.Groups[1].Value.Trim();
}
}
return string.Empty;
}
/// <summary>
/// Unicode字符转汉字 允许自定义分隔字符
/// </summary>
/// <param name="str">需要转换的字符串</param>
/// <param name="SplitString">分隔字符</param>
/// <param name="TrimStr">如果有尾部数据则填写尾部</param>
/// <returns>处理后结果</returns>
public string FromUnicodeString(string str, string SplitString = "u", string TrimStr = ";")
{
string regexCode = SplitString == "u" ? "\\\\u(\\w{1,4})" : SplitString + "(\\w{1,4})";
string reString = str;
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(regexCode);
System.Text.RegularExpressions.MatchCollection mc = reg.Matches(reString);
for (int i = 0; i < mc.Count; i++)
{
try
{
var outs = (char)int.Parse(mc[i].Groups[1].Value, System.Globalization.NumberStyles.HexNumber);
if (str.IndexOf(mc[i].Groups[0].Value + TrimStr) > 0)
{
//如果出现(封号);结尾则连带符号替换
str = str.Replace(mc[i].Groups[0].Value + TrimStr, outs.ToString());
}
else
{
str = str.Replace(mc[i].Groups[0].Value, outs.ToString());
}
}
catch
{
continue;
}
}
return str;
}
/// <summary>
/// 汉字转Unicode字符 默认\u1234
/// </summary>
/// <param name="param">需要转换的字符</param>
/// <param name="SplitString">分隔结果</param>
/// <returns>转换后结果</returns>
public string GetUnicodeString(string param, string SplitString = "u")
{
string outStr = "";
for (int i = 0; i < param.Length; i++)
{
try
{
outStr += "\\" + SplitString + ((int)param[i]).ToString("x4");
}
catch
{
outStr += param[i];
continue;
}
}
return outStr;
}
/// <summary>
/// 将字符串转换为base64格式 默认UTF8编码
/// </summary>
/// <param name="str">原始字符串</param>
/// <param name="encoding">编码</param>
/// <returns>结果</returns>
public string GetString2Base64(string str, Encoding encoding = null)
{
if (encoding == null)
{
encoding = Encoding.UTF8;
}
return Convert.ToBase64String(encoding.GetBytes(str));
}
/// <summary>
/// base64字符串转换为普通格式 默认UTF8编码
/// </summary>
/// <param name="str">原始字符串</param>
/// <param name="encoding">编码</param>
/// <returns>结果</returns>
public string GetStringbyBase64(string str, Encoding encoding = null)
{
if (encoding == null)
{
encoding = Encoding.UTF8;
}
byte[] buffer = Convert.FromBase64String(str);
return encoding.GetString(buffer);
}
/// <summary>
/// 将byte数组转换为AscII字符
/// </summary>
/// <param name="b">需要操作的数组</param>
/// <returns>结果</returns>
public string GetAscii2string(byte[] b)
{
string str = "";
for (int i = 7; i < 19; i++)
{
str += (char)b[i];
}
return str;
}
/// <summary>
/// 将字节数组转化为十六进制字符串,每字节表示为两位
/// </summary>
/// <param name="bytes">需要操作的数组</param>
/// <param name="start">起始位置</param>
/// <param name="len">长度</param>
/// <returns>字符串结果</returns>
public string Bytes2HexString(byte[] bytes, int start, int len)
{
string tmpStr = "";
for (int i = start; i < (start + len); i++)
{
tmpStr = tmpStr + bytes[i].ToString("X2");
}
return tmpStr;
}
/// <summary>
/// 字符串转16进制
/// </summary>
/// <param name="mHex">需要转换的字符串</param>
/// <returns>返回十六进制代表的字符串</returns>
public string HexToStr(string mHex) // 返回十六进制代表的字符串
{
byte[] bTemp = System.Text.Encoding.Default.GetBytes(mHex);
string strTemp = "";
for (int i = 0; i < bTemp.Length; i++)
{
strTemp += bTemp[i].ToString("X");
}
return strTemp;
}
/// <summary>
/// 将十六进制字符串转化为字节数组
/// </summary>
/// <param name="src">需要转换的字符串</param>
/// <returns>结果数据</returns>
public byte[] HexString2Bytes(string src)
{
byte[] retBytes = new byte[src.Length / 2];
for (int i = 0; i < src.Length / 2; i++)
{
retBytes[i] = byte.Parse(src.Substring(i * 2, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
}
return retBytes;
}
#endregion
#region Cookie维护处理方法
/// <summary>
/// 合并Cookie,将cookie2与cookie1合并更新 返回字符串类型Cookie
/// </summary>
/// <param name="cookie1">旧cookie</param>
/// <param name="cookie2">新cookie</param>
/// <returns></returns>
public string UpdateCookie(string cookie1, string cookie2)
{
StringBuilder sb = new StringBuilder();
Dictionary<string, string> dicCookie = new Dictionary<string, string>();
//遍历cookie1
if (!string.IsNullOrEmpty(cookie1))
{
foreach (string cookie in cookie1.Replace(',', ';').Split(';'))
{
if (!string.IsNullOrEmpty(cookie) && cookie.IndexOf('=') > 0)
{
string key = cookie.Split('=')[0].Trim();
string value = cookie.Substring(key.Length + 1).Trim();
if (dicCookie.ContainsKey(key))
{
dicCookie[key] = cookie;
}
else
{
dicCookie.Add(key, cookie);
}
}
}
}
if (!string.IsNullOrEmpty(cookie2))
{
//遍历cookie2
foreach (string cookie in cookie2.Replace(',', ';').Split(';'))
{
if (!string.IsNullOrEmpty(cookie) && cookie.IndexOf('=') > 0)
{
string key = cookie.Split('=')[0].Trim();
string value = cookie.Substring(key.Length + 1).Trim();
if (dicCookie.ContainsKey(key))
{
dicCookie[key] = cookie;
}
else
{
dicCookie.Add(key, cookie);
}
}
}
}
int i = 0;
foreach (var item in dicCookie)
{
i++;
if (i < dicCookie.Count)
{
sb.Append(item.Value + ";");
}
else
{
sb.Append(item.Value);
}
}
return sb.ToString();
}
/// <summary>
/// 清理string类型Cookie.剔除无用项返回结果为null时遇见错误.
/// </summary>
/// <param name="Cookies"></param>
/// <returns></returns>
public string ClearCookie(string Cookies)
{
try
{
string rStr = string.Empty;
Cookies = Cookies.Replace(";", "; ");
string clStr = "(?<cookie>[^ ]+=(?!deleted;)[^;]+);";
Again:
Regex r = new Regex(clStr);//"(?<=,)(?<cookie>[^ ]+=(?!deleted;)[^;]+);");
Match m = r.Match(Cookies);
while (m.Success)
{
rStr += m.Groups["cookie"].Value + ";";
m = m.NextMatch();
}
if (rStr.Contains("path"))
{
clStr = "(?<=,)(?<cookie>[^ ]+=(?!deleted;)[^;]+);";
rStr = rStr.Split(new string[] { "path" }, StringSplitOptions.RemoveEmptyEntries)[0];
}
return rStr;
}
catch
{
return string.Empty;
}
}
/// <summary>
/// 获取当前请求所有Cookie
/// </summary>
/// <param name="items"></param>
/// <returns>Cookie集合</returns>
public List<Cookie> GetAllCookieByHttpItems(HttpItems items)
{
return wnet.GetAllCookies(items.Container);
}
/// <summary>
/// 获取CookieContainer 中的所有对象
/// </summary>
/// <param name="cc"></param>
/// <returns></returns>
public List<Cookie> GetAllCookie(CookieContainer cc)
{
return wnet.GetAllCookies(cc);
}
/// <summary>
/// 将 CookieContainer 对象转换为字符串类型
/// </summary>
/// <param name="cc"></param>
/// <returns></returns>
public string CookieTostring(CookieContainer cc)
{
return wnet.CookieToString(cc);
}
/// <summary>
/// 将文字Cookie转换为CookieContainer 对象
/// </summary>
/// <param name="url"></param>
/// <param name="cookie"></param>
/// <returns></returns>
public CookieContainer StringToCookie(string url, string cookie)
{