C# 监听HTTP请求(遇到的一些问题)
先把代码放在这里,下面再详细解说:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Oracle.DataAccess.Client;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web; namespace ConsoleApplication1
{
class Program
{
static Object o = new object();
static void Main(string[] args)
{
HttpListener listerner = new HttpListener();
while (true)
{
try
{
listerner.AuthenticationSchemes = AuthenticationSchemes.Anonymous;//指定身份验证 Anonymous匿名访问
listerner.Prefixes.Add("http://127.0.0.1:1500/Service/");
listerner.Start();
}
catch (Exception ex)
{
Console.WriteLine("服务启动失败...");
break;
}
Console.WriteLine("服务器启动成功......."); //线程池
int minThreadNum;
int portThreadNum;
int maxThreadNum;
ThreadPool.GetMaxThreads(out maxThreadNum, out portThreadNum);
ThreadPool.GetMinThreads(out minThreadNum, out portThreadNum);
Console.WriteLine("最大线程数:{0}", maxThreadNum);
Console.WriteLine("最小空闲线程数:{0}", minThreadNum);
//ThreadPool.QueueUserWorkItem(new WaitCallback(TaskProc1), x); Console.WriteLine("\n\n等待客户连接中。。。。");
while (true)
{
//等待请求连接
//没有请求则GetContext处于阻塞状态
HttpListenerContext ctx = listerner.GetContext(); ThreadPool.QueueUserWorkItem(new WaitCallback(TaskProc), ctx);
}
//listerner.Stop();
} Console.ReadKey();
} static void TaskProc(object o)
{
HttpListenerContext ctx = (HttpListenerContext)o; ctx.Response.StatusCode = 200;//设置返回给客服端http状态代码 //接收Get参数
string type = ctx.Request.QueryString["type"];
string userId = ctx.Request.QueryString["userId"];
string password = ctx.Request.QueryString["password"];
string filename = Path.GetFileName(ctx.Request.RawUrl);
string userName = HttpUtility.ParseQueryString(filename).Get("userName");//避免中文乱码
//进行处理
Console.WriteLine("收到数据:" + userName); //接收POST参数
Stream stream = ctx.Request.InputStream;
System.IO.StreamReader reader = new System.IO.StreamReader(stream, Encoding.UTF8);
String body = reader.ReadToEnd();
Console.WriteLine("收到POST数据:" + HttpUtility.UrlDecode(body));
Console.WriteLine("解析:" + HttpUtility.ParseQueryString(body).Get("userName")); //使用Writer输出http响应代码,UTF8格式
using (StreamWriter writer = new StreamWriter(ctx.Response.OutputStream,Encoding.UTF8))
{
writer.Write("处理结果,Hello world<br/>");
writer.Write("数据是userId={0},userName={1}", userId, userName);
writer.Close();
ctx.Response.Close();
}
} } }

1.可通过HttpUtility.UrlDecode对传入的参数进行解码,防止中文乱码
2.StreamWriter必须使用UTF8格式,防止中文乱码
3.微软提供的HttpListener默认不能接收POST参数,所以需要自己去解析,上面已实现
4.界面可通过form的post方式直接提交数据
public void AddAddress(string address)
{
try
{
AddAddress(address, Environment.UserDomainName, Environment.UserName);
}
catch (Exception ex) { }
} public void AddAddress(string address, string domain, string user)
{
string argsDll = String.Format(@"http delete urlacl url={0}", address);
string args = string.Format(@"http add urlacl url={0} user={1}\{2}", address, domain, user);
ProcessStartInfo psi = new ProcessStartInfo("netsh", argsDll);
psi.Verb = "runas";
psi.CreateNoWindow = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
Process.Start(psi).WaitForExit();//删除urlacl
psi = new ProcessStartInfo("netsh", args);
psi.Verb = "runas";
psi.CreateNoWindow = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
Process.Start(psi).WaitForExit();//添加urlacl
}
用法:AddAddress("http://127.0.0.1:1500/Service/Setup/");,同时启动程序的要用管理员权限运行。
step2、选择windows防火墙,点击高级设置
step3、在弹出的“高级安全windows防火墙”点击“入站规则”,在右侧“操作”栏点击“入站规则”下的“新建规则…”,此时会弹出一个窗口让你设置。剩下的就非常傻瓜化了。
step4、弹出“新建入站规则向导”-规则类型-选中“端口”,点击下一步。选择规则应用的协议“TCP/UDP”如果是TCP你就选择TCP,UDP就选择UDP。再勾选“特定本地端口”在文本框输入您想开放的端口号(例如1521)。
step5、点击下一步,到“连接符合指定条件时应该进行什么操作?”选择“允许连接”。点击下一步到“配置文件”何时应用该规则,勾选“域”、“专用”、“公用”点击下一步。
step6、配置规则名称,随便输入你自己认为好记的规则名称即可。
4.你可能还会遇到下面这个问题:HTTP Error 503
如果你运行程序的电脑遇到了这个问题,就这样把你上面的ip改成+号;例如:http://127.0.0.1:1500/Service/Setup/改成http://+:1500/Service/Setup/
记住AddAddress和listerner.Prefixes.Add里的ip都要改
C# 监听HTTP请求(遇到的一些问题)的更多相关文章
- 李洪强iOS开发本人集成环信的经验总结_07_监听好友请求
李洪强iOS开发本人集成环信的经验总结_07_监听好友请求 来到Appdalegate中: 遵守代理协议 设置代理 实现监听好友请求的回调的方法
- 怎样监听HTTP请求的发出与完成
1. 监听HTTP请求发出的事件是: xhr.onloadstart 2. 监听HTTP请求结束的事件是: xhr.onloadend xhr.onloadstart = function() { / ...
- Spring Boot实现一个监听用户请求的拦截器
项目中需要监听用户具体的请求操作,便通过一个拦截器来监听,并继续相应的日志记录 项目构建与Spring Boot,Spring Boot实现一个拦截器很容易. Spring Boot的核心启动类继承W ...
- nginx源代码分析--监听套接字的创建 套接字的监听 HTTP请求创建连接
作为一个webserver,那么肯定是有监听套接字的,这个监听套接字是用于接收HTTP请求的,这个监听套接字的创建是依据配置文件的内容来创建的,在nginx.conf文件里有多少个地址就须要创建多少个 ...
- 怎样监听HTTP请求的成功、失败与进行时
1. 监听请求成功: xhr.onload 2. 监听请求失败: xhr.onerror 3. 监听请求数据下载中: xhr.onprogress xhr.onload = function() { ...
- j2ee之监听页面请求
本博客的起因是我想监听浏览器端每个页面都访问了哪些资源~~: 我是个菜鸡,所以我要记在我的小本本上,我怕忘了又~~~: 代码我是写在springboot2.1中的,有兴趣的同学可以玩一下~ 1:代码如 ...
- js 监听ajax请求
function hookSend(hook) { if (!XMLHttpRequest.prototype._oldSend) XMLHttpRequest.prototype._oldSend ...
- Fiddler监听Https请求响应
Fiddler问题 - creation of the root certificate was not successful 解决办法: http://localhost:8888/ 安装证书 ...
- 监听HTTP请求
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Oracle.DataAccess.Client; using System; usi ...
- C# 监听HTTP请求
先把代码放在这里,下面再详细解说: using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Oracle.DataAccess.Client; ...
随机推荐
- SSH 远程端口转发
既然"本地端口转发"是指绑定本地端口的转发,那么"远程端口转发"(remote forwarding)当然是指绑定远程端口的转发. 还是接着看上面那个例子,ho ...
- Splunk Enterprise architecture——转发器本质上是日志收集client附加负载均衡,indexer是分布式索引,外加一个集中式管理协调的中心节点
Splunk Enterprise architecture and processes This topic discusses the internal architecture and proc ...
- tensoflow学习入门一
对于如何创建图并开启session,参考如下 # -- encoding:utf-8 -- import tensorflow as tf # 定义常量矩阵a和矩阵b a=tf.constant([[ ...
- 遍历HashMap的方法(四)
Map map = new HashMap(); for (Iterator iter = map.entrySet().iterator(); iter.hasNext();) { Map.Entr ...
- hdu4800 Josephina and RPG 解题报告
Josephina and RPG Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others ...
- 集合list里存储list,要遍历最底层list的对象元素的遍历方法
package com.wtd; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; im ...
- Linux Mint KDE上安装fcitx+sougou输入法
今天在韩总废弃的笔记本上安装了Linux Mint系统,装好之后第一件想到的事情就是安装个输入法,由于之前系统自带的输入法框架是ibus,我试用了一下发现很不人性化,所以决定换上fcitx+sougo ...
- QAV250四轴穿越机安装全程详解(多图)
QAV250四轴穿越机安装全程详解 最近团队准备使用轻型穿越机QAV250做实验,本文记录了QAV250的安装过程,整理了开箱后较合理的安装顺序,以及各个步骤的注意事项,希望对有需要的朋友有所帮助.主 ...
- 转:window.orientation判断移动设备横屏竖屏
通过window.orientation来判断设备横竖屏 function checkOrient() { if (window.orientation == 0 || window.orientat ...
- error: QXcbConnection: Could not connect to display
/********************************************************************************* * error: QXcbConn ...