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

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# 6.0知识点

    三十分钟快速掌握C# 6.0知识点

    这篇文章主要介绍了C# 6.0的相关知识点,文中介绍的非常详细,通过这篇文字可以让大家在三十分钟内快速的掌握C# 6.0,需要的朋友可以参考借鉴,下面来...

    雨夜潇湘8272021-12-28
  • C#SQLite在C#中的安装与操作技巧

    SQLite在C#中的安装与操作技巧

    SQLite,是一款轻型的数据库,用于本地的数据储存。其优点有很多,下面通过本文给大家介绍SQLite在C#中的安装与操作技巧,感兴趣的的朋友参考下吧...

    蓝曈魅11162022-01-20
  • C#如何使用C#将Tensorflow训练的.pb文件用在生产环境详解

    如何使用C#将Tensorflow训练的.pb文件用在生产环境详解

    这篇文章主要给大家介绍了关于如何使用C#将Tensorflow训练的.pb文件用在生产环境的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考借鉴...

    bbird201811792022-03-05
  • C#C#设计模式之Strategy策略模式解决007大破密码危机问题示例

    C#设计模式之Strategy策略模式解决007大破密码危机问题示例

    这篇文章主要介绍了C#设计模式之Strategy策略模式解决007大破密码危机问题,简单描述了策略模式的定义并结合加密解密算法实例分析了C#策略模式的具体使用...

    GhostRider10972022-01-21
  • C#VS2012 程序打包部署图文详解

    VS2012 程序打包部署图文详解

    VS2012虽然没有集成打包工具,但它为我们提供了下载的端口,需要我们手动安装一个插件InstallShield。网上有很多第三方的打包工具,但为什么偏要使用微软...

    张信秀7712021-12-15
  • C#深入理解C#的数组

    深入理解C#的数组

    本篇文章主要介绍了C#的数组,数组是一种数据结构,详细的介绍了数组的声明和访问等,有兴趣的可以了解一下。...

    佳园9492021-12-10
  • C#利用C#实现网络爬虫

    利用C#实现网络爬虫

    这篇文章主要介绍了利用C#实现网络爬虫,完整的介绍了C#实现网络爬虫详细过程,感兴趣的小伙伴们可以参考一下...

    C#教程网11852021-11-16
  • C#C#微信公众号与订阅号接口开发示例代码

    C#微信公众号与订阅号接口开发示例代码

    这篇文章主要介绍了C#微信公众号与订阅号接口开发示例代码,结合实例形式简单分析了C#针对微信接口的调用与处理技巧,需要的朋友可以参考下...

    smartsmile20127762021-11-25