如何截取Http请求

本文介绍了一个简单的HTTP服务器实现,该服务器能够截取HTTP请求并作出响应。使用C#的HttpListener类来监听端口,当接收到请求时,服务器会返回一个固定的HTML页面告知请求已被截取。

1:前言

    本篇文章比较短,主要是因为我的一个随想产生的一段代码。 这段代码的功能你可以叫做是简单的Http服务器也可以叫做Http请求截取。它实现的功能就是截取Http请求然后自己做处理。

2:代码

代码
    public class HttpServer : IDisposable
    {

        
private HttpListener listener;

        
public void Start()
        {
            listener 
= new HttpListener();
            listener.Prefixes.Add(
"http://localhost/");
            
            listener.AuthenticationSchemes 
= AuthenticationSchemes.IntegratedWindowsAuthentication | AuthenticationSchemes.Anonymous;

            listener.Start();
            listener.BeginGetContext(GetContext, 
null);
        }

        
private void GetContext(IAsyncResult ar)
        {
            HttpListenerRequest Request;
            HttpListenerResponse Response;

            
try
            {
                HttpListenerContext ctx 
= listener.EndGetContext(ar);
                Request 
= ctx.Request;
                Response 
= ctx.Response;

                
//setup waiting for the next request
                listener.BeginGetContext(GetContext, null);
            }
            
catch (InvalidOperationException)
            {
                
return;
            }
            
catch (HttpListenerException)
            {
                
return;
            }

            
try
            {
                var sw 
= new StreamWriter(Response.OutputStream);
                sw.Write(
@"<html><body><p>你的请求已经被截取</p></body></html>");
                sw.Flush();
            }
            
finally
            {
                Response.OutputStream.Flush();
                Response.Close();
            }

        }

        
public void Dispose()
        {
            
if (listener != null)
                listener.Stop();
        }
    }

 

3:简单解释一下

    代码的核心就是HttpListener,通过它去侦听一个端口,当有请求的时候BeginGetContext交给GetContext方法进行异步处理,在这个方法的内部首先实现的就是重新监听。然后进行自己的处理。

    呵呵,这段代码有什么其他用处待考虑。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值