服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - c#使用Socket发送HTTP/HTTPS请求的实现代码

c#使用Socket发送HTTP/HTTPS请求的实现代码

2022-01-21 13:47C#教程网 C#

这篇文章主要介绍了c#使用Socket发送HTTP/HTTPS请求的实现代码,需要的朋友可以参考下

c# 自带的httpwebrequest效率太低,对于自组http封包不好操作。

在写超级sql注入工具时,研究了很长一段时间如何使用socket来发送http、https请求。

经过一年的修改和测试,可完美、高效发送并解析http/https请求。修改过无数次bug。

在这里把核心代码分享出来,供大家学习或做开发参考。

用这个代码写了一个简单的http发包工具。供大家参考。

c#使用Socket发送HTTP/HTTPS请求的实现代码

工具下载:

httptool.rar

核心类:http.cs

?
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
using system;
using system.collections.generic;
using system.text;
using tools;
using system.net;
using system.net.sockets;
using system.io.compression;
using system.io;
using system.net.security;
using system.text.regularexpressions;
using system.threading;
using system.diagnostics;
using system.security.authentication;
using system.security.cryptography.x509certificates;
using httptool;
 
namespace tools
{
  public class http
  {
    public const char t = '
';
    public const string ct = "
";
    public const string ctrl = "
 
";
    public const string content_length_str = "content-length: ";
    public const string content_length_str_m = "content-length: ";
    public const string content_length = "content-length";
    public const string content_encoding = "content-encoding";
    public const string transfer_encoding = "transfer-encoding";
    public const string connection = "connection";
    public static main main = null;
    public static long index = 0;
    public void initmain(main m)
    {
      main = m;
    }
 
    /**
     *
     发生异常尝试重连
     *
     */
    public static serverinfo sendrequestretry(boolean isssl, int trycount, string host, int port, string payload, string request, int timeout, string encoding, boolean foward_302)
    {
      int count = 0;
      interlocked.increment(ref index);
      serverinfo server = new serverinfo();
      timeout = timeout * 1000;
      while (true)
      {
        if (count >= trycount) break;
 
        try
        {
          if (!isssl)
          {
            server = sendhttprequest(count, host, port, payload, request, timeout, encoding, foward_302);
            return server;
          }
          else
          {
 
            server = sendhttpsrequest(count, host, port, payload, request, timeout, encoding, foward_302);
            return server;
 
          }
        }
        catch (exception e)
        {
          tools.syslog("发包发生异常,正在重试----" + e.message);
          server.timeout = true;
          continue;
        }
        finally
        {
          count++;
        }
 
      }
      return server;
 
    }
 
    private static void checkcontentlength(ref serverinfo server, ref string request)
    {
 
      //重新计算并设置content-length
      int sindex = request.indexof(ctrl);
      server.reuqestheader = request;
      if (sindex != -1)
      {
        server.reuqestheader = request.substring(0, sindex);
        server.reuqestbody = request.substring(sindex + 4, request.length - sindex - 4);
        int contentlength = encoding.utf8.getbytes(server.reuqestbody).length;
        string newcontentlength = content_length_str_m + contentlength;
 
        if (request.indexof(content_length_str_m) != -1)
        {
          request = regex.replace(request, content_length_str_m + "d+", newcontentlength);
        }
        else
        {
          request = request.insert(sindex, "
" + newcontentlength);
        }
      }
      else
      {
        request = regex.replace(request, content_length_str + "d+", content_length_str_m + "0");
        request += ctrl;
      }
 
 
    }
 
    private static void doheader(ref serverinfo server, ref string[] headers)
    {
 
      for (int i = 0; i < headers.length; i++)
      {
        if (i == 0)
        {
 
          server.code = tools.converttoint(headers[i].split(' ')[1]);
 
        }
        else
        {
          string[] kv = regex.split(headers[i], ": ");
          string key = kv[0].tolower();
          if (!server.headers.containskey(key))
          {
            //自动识别编码
            if ("content-type".equals(key))
            {
              string hecnode = gethtmlencoding(kv[1], "");
              if (!string.isnullorempty(hecnode))
              {
                server.encoding = hecnode;
              }
            }
            if (kv.length > 1)
            {
              server.headers.add(key, kv[1]);
            }
            else
            {
              server.headers.add(key, "");
            }
          }
        }
      }
 
    }
 
 
    private static serverinfo sendhttprequest(int count, string host, int port, string payload, string request, int timeout, string encoding, boolean foward_302)
    {
 
      string index = thread.currentthread.name + http.index;
      stopwatch sw = new stopwatch();
      sw.start();
      serverinfo server = new serverinfo();
      tcpclient clientsocket = null;
      int sum = 0;
      try
      {
        if (port > 0 && port <= 65556)
        {
          //编码处理
          server.request = request;
          timeoutsocket tos = new timeoutsocket();
          clientsocket = tos.connect(host, port, timeout);
          if (sw.elapsedmilliseconds >= timeout)
          {
            return server;
          }
          clientsocket.sendtimeout = timeout - tos.usetime;
          if (clientsocket.connected)
          {
            checkcontentlength(ref server, ref request);
            server.request = request;
 
            byte[] requestbyte = encoding.utf8.getbytes(request);
            clientsocket.client.send(requestbyte);
            byte[] responsebody = new byte[1024 * 1000];
            int len = 0;
            //获取header头
            string tmp = "";
            stringbuilder sb = new stringbuilder();
            clientsocket.receivetimeout = timeout - (int)sw.elapsedmilliseconds;
            do
            {
              byte[] responseheader = new byte[1];
              len = clientsocket.client.receive(responseheader, 1, socketflags.none);
              if (len == 1)
              {
 
                char c = (char)responseheader[0];
                sb.append(c);
                if (c.equals(t))
                {
                  tmp = string.concat(sb[sb.length - 4], sb[sb.length - 3], sb[sb.length - 2], c);
                }
              }
            } while (!tmp.equals(ctrl) && sw.elapsedmilliseconds < timeout);
 
            server.header = sb.tostring().replace(ctrl, "");
            string[] headers = regex.split(server.header, ct);
            if (headers != null && headers.length > 0)
            {
              //处理header
              doheader(ref server, ref headers);
              //自动修正编码
              if (!string.isnullorempty(server.encoding))
              {
                encoding = server.encoding;
              }
              encoding encod = encoding.getencoding(encoding);
 
              //302 301跳转
              if ((server.code == 302 || server.code == 301) && foward_302)
              {
                stringbuilder rsb = new stringbuilder(server.request);
                int urlstart = server.request.indexof(" ") + 1;
                int urlend = server.request.indexof(" http");
                if (urlstart != -1 && urlend != -1)
                {
                  string url = server.request.substring(urlstart, urlend - urlstart);
                  rsb.remove(urlstart, url.length);
                  string location = server.headers["location"];
                  if (!server.headers["location"].startswith("/") && !server.headers["location"].startswith("http"))
                  {
                    location = tools.getcurrentpath(url) + location;
                  }
                  rsb.insert(urlstart, location);
 
                  return sendhttprequest(count, host, port, payload, rsb.tostring(), timeout, encoding, false);
                }
 
              }
 
 
              //根据请求头解析
              if (server.headers.containskey(content_length))
              {
                int length = int.parse(server.headers[content_length]);
 
                while (sum < length && sw.elapsedmilliseconds < timeout)
                {
                  int readsize = length - sum;
                  len = clientsocket.client.receive(responsebody, sum, readsize, socketflags.none);
                  if (len > 0)
                  {
                    sum += len;
                  }
                }
              }
              //解析chunked传输
              else if (server.headers.containskey(transfer_encoding))
              {
                //读取长度
                int chunkedsize = 0;
                byte[] chunkedbyte = new byte[1];
                //读取总长度
                sum = 0;
                do
                {
                  string ctmp = "";
                  do
                  {
                    len = clientsocket.client.receive(chunkedbyte, 1, socketflags.none);
                    ctmp += encoding.utf8.getstring(chunkedbyte);
 
                  } while ((ctmp.indexof(ct) == -1) && (sw.elapsedmilliseconds < timeout));
 
                  chunkedsize = tools.converttointby16(ctmp.replace(ct, ""));
 
                  //chunked的结束0
 
是结束标志,单个chunked块
结束
                  if (ctmp.equals(ct))
                  {
                    continue;
                  }
                  if (chunkedsize == 0)
                  {
                    //结束了
                    break;
                  }
                  int onechunklen = 0;
                  while (onechunklen < chunkedsize && sw.elapsedmilliseconds < timeout)
                  {
                    len = clientsocket.client.receive(responsebody, sum, chunkedsize - onechunklen, socketflags.none);
                    if (len > 0)
                    {
                      onechunklen += len;
                      sum += len;
                    }
                  }
 
                  //判断
                } while (sw.elapsedmilliseconds < timeout);
              }
              //connection close方式或未知body长度
              else
              {
                while (sw.elapsedmilliseconds < timeout)
                {
                  if (clientsocket.client.poll(timeout, selectmode.selectread))
                  {
                    if (clientsocket.available > 0)
                    {
                      len = clientsocket.client.receive(responsebody, sum, (1024 * 200) - sum, socketflags.none);
                      if (len > 0)
                      {
                        sum += len;
                      }
                    }
                    else
                    {
                      break;
                    }
                  }
                }
              }
              //判断是否gzip
              if (server.headers.containskey(content_encoding))
              {
                server.body = ungzip(responsebody, sum, encod);
              }
              else
              {
                server.body = encod.getstring(responsebody, 0, sum);
              }
 
 
            }
          }
 
        }
      }
      catch (exception e)
      {
        exception ee = new exception("http发包错误!错误消息:" + e.message + e.targetsite.name + "----发包编号:" + index);
        throw ee;
      }
      finally
      {
        sw.stop();
        server.length = sum;
        server.runtime = (int)sw.elapsedmilliseconds;
        if (clientsocket != null)
        {
          clientsocket.close();
        }
      }
      return server;
 
    }
 
    private static bool validateservercertificate(object sender, x509certificate certificate, x509chain chain, sslpolicyerrors sslpolicyerrors)
    {
      return true;
    }
    private static serverinfo sendhttpsrequest(int count, string host, int port, string payload, string request, int timeout, string encoding, boolean foward_302)
    {
      string index = thread.currentthread.name + http.index;
      stopwatch sw = new stopwatch();
      sw.start();
      serverinfo server = new serverinfo();
 
      int sum = 0;
 
      tcpclient clientsocket = null; ;
 
      try
      {
 
        if (port > 0 && port <= 65556)
        {
 
          timeoutsocket tos = new timeoutsocket();
          clientsocket = tos.connect(host, port, timeout);
          if (sw.elapsedmilliseconds >= timeout)
          {
            return server;
          }
          clientsocket.sendtimeout = timeout - tos.usetime;
 
          sslstream ssl = null;
          if (clientsocket.connected)
          {
            ssl = new sslstream(clientsocket.getstream(), false, new remotecertificatevalidationcallback(validateservercertificate));
            sslprotocols protocol = sslprotocols.ssl3 | sslprotocols.ssl2 | sslprotocols.tls;
            ssl.authenticateasclient(host, null, protocol, false);
            if (ssl.isauthenticated)
            {
              checkcontentlength(ref server, ref request);
              server.request = request;
              byte[] requestbyte = encoding.utf8.getbytes(request);
              ssl.write(requestbyte);
              ssl.flush();
            }
          }
          server.request = request;
          byte[] responsebody = new byte[1024 * 1000];
          int len = 0;
          //获取header头
          string tmp = "";
 
          stringbuilder sb = new stringbuilder();
          stringbuilder bulider = new stringbuilder();
          clientsocket.receivetimeout = timeout - (int)sw.elapsedmilliseconds;
          do
          {
            byte[] responseheader = new byte[1];
            int read = ssl.readbyte();
 
            char c = (char)read;
            sb.append(c);
            if (c.equals(t))
            {
              tmp = string.concat(sb[sb.length - 4], sb[sb.length - 3], sb[sb.length - 2], c);
            }
 
          } while (!tmp.equals(ctrl) && sw.elapsedmilliseconds < timeout);
 
          server.header = sb.tostring().replace(ctrl, "");
          string[] headers = regex.split(server.header, ct);
          //处理header
          doheader(ref server, ref headers);
          //自动修正编码
          if (!string.isnullorempty(server.encoding))
          {
            encoding = server.encoding;
          }
          encoding encod = encoding.getencoding(encoding);
          //302 301跳转
          if ((server.code == 302 || server.code == 301) && foward_302)
          {
 
            int urlstart = server.request.indexof(" ");
            int urlend = server.request.indexof(" http");
            if (urlstart != -1 && urlend != -1)
            {
              string url = server.request.substring(urlstart + 1, urlend - urlstart - 1);
              if (!server.headers["location"].startswith("/") && !server.headers["location"].startswith("https"))
              {
                server.request = server.request.replace(url, tools.getcurrentpath(url) + server.headers["location"]);
              }
              else
              {
                server.request = server.request.replace(url, server.headers["location"]);
              }
 
              return sendhttpsrequest(count, host, port, payload, server.request, timeout, encoding, false);
            }
 
          }
 
 
          //根据请求头解析
          if (server.headers.containskey(content_length))
          {
            int length = int.parse(server.headers[content_length]);
            while (sum < length && sw.elapsedmilliseconds < timeout)
            {
              len = ssl.read(responsebody, sum, length - sum);
              if (len > 0)
              {
                sum += len;
              }
            }
          }
          //解析chunked传输
          else if (server.headers.containskey(transfer_encoding))
          {
            //读取长度
            int chunkedsize = 0;
            byte[] chunkedbyte = new byte[1];
            //读取总长度
            sum = 0;
            do
            {
              string ctmp = "";
              do
              {
                len = ssl.read(chunkedbyte, 0, 1);
                ctmp += encoding.utf8.getstring(chunkedbyte);
 
              } while (ctmp.indexof(ct) == -1 && sw.elapsedmilliseconds < timeout);
 
              chunkedsize = tools.converttointby16(ctmp.replace(ct, ""));
 
              //chunked的结束0
 
是结束标志,单个chunked块
结束
              if (ctmp.equals(ct))
              {
                continue;
              }
              if (chunkedsize == 0)
              {
                //结束了
                break;
              }
              int onechunklen = 0;
 
              while (onechunklen < chunkedsize && sw.elapsedmilliseconds < timeout)
              {
                len = ssl.read(responsebody, sum, chunkedsize - onechunklen);
                if (len > 0)
                {
                  onechunklen += len;
                  sum += len;
                }
              }
 
              //判断
            } while (sw.elapsedmilliseconds < timeout);
          }
          //connection close方式或未知body长度
          else
          {
            while (sw.elapsedmilliseconds < timeout)
            {
              if (clientsocket.client.poll(timeout, selectmode.selectread))
              {
                if (clientsocket.available > 0)
                {
                  len = ssl.read(responsebody, sum, (1024 * 200) - sum);
                  if (len > 0)
                  {
                    sum += len;
                  }
                }
                else
                {
                  break;
                }
              }
            }
          }
          //判断是否gzip
          if (server.headers.containskey(content_encoding))
          {
            server.body = ungzip(responsebody, sum, encod);
          }
          else
          {
            server.body = encod.getstring(responsebody, 0, sum);
          }
        }
 
      }
      catch (exception e)
      {
        exception ee = new exception("https发包错误!错误消息:" + e.message + "----发包编号:" + index);
        throw ee;
      }
      finally
      {
        sw.stop();
        server.length = sum;
        server.runtime = (int)sw.elapsedmilliseconds;
 
        if (clientsocket != null)
        {
          clientsocket.close();
        }
      }
      return server;
 
    }
 
    public static string ungzip(byte[] data, int len, encoding encoding)
    {
 
      string str = "";
      memorystream ms = new memorystream(data, 0, len);
      gzipstream gs = new gzipstream(ms, compressionmode.decompress);
      memorystream outbuf = new memorystream();
      byte[] block = new byte[1024];
 
      try
      {
 
        while (true)
        {
          int bytesread = gs.read(block, 0, block.length);
          if (bytesread <= 0)
          {
            break;
          }
          else
          {
            outbuf.write(block, 0, bytesread);
          }
        }
        str = encoding.getstring(outbuf.toarray());
      }
      catch (exception e)
      {
        tools.syslog("解压gzip发生异常----" + e.message);
      }
      finally
      {
        outbuf.close();
        gs.close();
        ms.close();
 
      }
      return str;
 
    }
    public static string gethtmlencoding(string header, string body)
    {
      if (string.isnullorempty(header) && string.isnullorempty(body))
      {
        return "";
      }
      body = body.toupper();
      match m = regex.match(header, @"charsets*=s*""?(?<charset>[^""]*)", regexoptions.ignorecase);
      if (m.success)
      {
        return m.groups["charset"].value.toupper();
      }
      else
      {
        if (string.isnullorempty(body))
        {
          return "";
        }
        m = regex.match(body, @"charsets*=s*""?(?<charset>[^""]*)", regexoptions.ignorecase);
        if (m.success)
        {
          return m.groups["charset"].value.toupper();
        }
      }
      return "";
    }
  }
}

以上就是关于c# socket发送http/https请求的核心代码了,需要的朋友可以参考一下。

延伸 · 阅读

精彩推荐
  • C#C#直线的最小二乘法线性回归运算实例

    C#直线的最小二乘法线性回归运算实例

    这篇文章主要介绍了C#直线的最小二乘法线性回归运算方法,实例分析了给定一组点,用最小二乘法进行线性回归运算的实现技巧,具有一定参考借鉴价值,需要...

    北风其凉8912021-10-18
  • C#C#基础之泛型

    C#基础之泛型

    泛型是 2.0 版 C# 语言和公共语言运行库 (CLR) 中的一个新功能。接下来通过本文给大家介绍c#基础之泛型,感兴趣的朋友一起学习吧...

    方小白7732021-12-03
  • C#C# 后台处理图片的几种方法

    C# 后台处理图片的几种方法

    本篇文章主要介绍了C# 后台处理图片的几种方法,非常具有实用价值,需要的朋友可以参考下。...

    IT小伙儿10162021-12-08
  • C#聊一聊C#接口问题 新手速来围观

    聊一聊C#接口问题 新手速来围观

    聊一聊C#接口问题,新手速来围观,一个通俗易懂的例子帮助大家更好的理解C#接口问题,感兴趣的小伙伴们可以参考一下...

    zenkey7072021-12-03
  • C#C#实现的文件操作封装类完整实例【删除,移动,复制,重命名】

    C#实现的文件操作封装类完整实例【删除,移动,复制,重命名】

    这篇文章主要介绍了C#实现的文件操作封装类,结合完整实例形式分析了C#封装文件的删除,移动,复制,重命名等操作相关实现技巧,需要的朋友可以参考下...

    Rising_Sun3892021-12-28
  • C#Unity3D UGUI实现缩放循环拖动卡牌展示效果

    Unity3D UGUI实现缩放循环拖动卡牌展示效果

    这篇文章主要为大家详细介绍了Unity3D UGUI实现缩放循环拖动展示卡牌效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参...

    诗远3662022-03-11
  • C#浅谈C# winForm 窗体闪烁的问题

    浅谈C# winForm 窗体闪烁的问题

    下面小编就为大家带来一篇浅谈C# winForm 窗体闪烁的问题。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    C#教程网7962021-12-21
  • C#c#学习之30分钟学会XAML

    c#学习之30分钟学会XAML

    一个界面程序的核心,无疑就是界面和后台代码,而xaml就是微软为构建应用程序界面而创建的一种描述性语言,也就是说,这东西是搞界面的...

    C#教程网8812021-12-10