using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using System.Security.Cryptography;
using System.Collections.Specialized;
using System.Text;
using System.Web;
namespace HttpListenerTest
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main ()
{
Application.EnableVisualStyles ();
Application.SetCompatibleTextRenderingDefault (false);
string sendMsg = "hello word";
sendToRetUrl ("http://127.0.0.1:12345/aa.aspx?",sendMsg);
start ();
}
private static Thread threads = null;
private static System.Net.HttpListener listener = null;
public static void start ()
{
try
{
//开启一个处理Socket客户端通信的线程
threads = new Thread (new ThreadStart (startListener));
threads.Start ();
}
catch (Exception se)
{
Console.WriteLine (se.ToString ());
}
}
//开启http监听
public static void startListener ()
{
Console.WriteLine ("-----------------");
try
{
bool flag = true;
if (listener == null)
{
listener = new System.Net.HttpListener ();
listener.Prefixes.Add ("http://127.0.0.1:55555/");//监听所有ip地址为127.0.0.1,端口为55555的地址
}
listener.Start ();
while (flag)
{
try
{
IAsyncResult result = listener.BeginGetContext (EndGetRequest,listener);
result.AsyncWaitHandle.WaitOne ();
}
catch (Exception e)
{
break;
}
}
}
catch (Exception e1)
{
Console.WriteLine ("服务器Http方式监听报错:最终错误:" + e1.Message + "\r\n错误原因:" + e1.StackTrace);
}
}
public static System.Net.HttpListenerContext context = null;
public static void EndGetRequest (IAsyncResult result)
{
Console.WriteLine ("--------返回来了-------");
byte[] sendData = null;
System.Net.HttpListener listener = null;
try
{
listener = (System.Net.HttpListener)result.AsyncState;
// System.Net.HttpListenerContext context = (System.Net.HttpListenerContext)param;
if (listener != null && listener.IsListening)
{
context = listener.EndGetContext (result);
// context.Response.ContentEncoding = System.Text.Encoding.UTF8;
string requestOrder = context.Request.Url.AbsolutePath;
string paramQuery = context.Request.Url.Query;
paramQuery = HttpUtility.UrlDecode (paramQuery,Encoding.UTF8);
Console.WriteLine ("requestOrder=" + requestOrder + "------paramQuery=" + paramQuery);
if (requestOrder.Contains ("OrderMsg.aspx") && paramQuery.Contains ("&SignMsg="))
{
string realQuery = paramQuery.Substring (1);
Console.WriteLine ("------" + realQuery);
string orgParam = realQuery.Substring (0,realQuery.IndexOf ("&SignMsg"));
Console.WriteLine ("参数:" + orgParam);
string orgMsg = "Airepay2012" + orgParam;
string SignMsg = realQuery.Substring (realQuery.IndexOf ("&SignMsg=")+9);
Console.WriteLine ("SignMsg===" + SignMsg);
//context.Request.QueryString["SignMsg"]
if (checkSign (orgMsg,SignMsg))
{
NameValueCollection paramValue = context.Request.QueryString;
Console.WriteLine ("获取到信息为:" + orgParam);
//string retMsg = receiveAndSend (paramValue);
// sendData = context.Request.ContentEncoding.GetBytes (retMsg);
sendData = context.Request.ContentEncoding.GetBytes ("发送数据成功接收");
}
else
{
sendData = context.Request.ContentEncoding.GetBytes ("请求验证签名失败");
Console.WriteLine ("请求验证签名失败");
}
}
else
{
Console.WriteLine ("非法请求");
sendData = context.Request.ContentEncoding.GetBytes ("非法请求");
}
}
}
catch (Exception ex)
{
Console.Write ("Exception in listener: {0}{1}",Environment.NewLine,ex);
if (context != null)
sendData = context.Request.ContentEncoding.GetBytes ("系统错误");
}
finally
{
if (context != null)
{
context.Response.ContentEncoding = System.Text.Encoding.UTF8;
context.Response.Close (sendData,true);
}
// if (listener.IsListening)
// listener.BeginGetContext(EndGetRequest, listener);
}
}
//验证签名
public static bool checkSign (string orgMsg,string signedMsg)
{
bool flag = false;
if (orgMsg != null && signedMsg != null)
{
string newSignedMsg = MD5ToString (orgMsg);
flag = newSignedMsg.Equals (signedMsg.ToLower (),StringComparison.CurrentCulture);
}
return flag;
}
//MD5加密验证
private static string MD5ToString (String argString)
{
MD5 md5 = new MD5CryptoServiceProvider ();
byte[] data = System.Text.Encoding.UTF8.GetBytes (argString);
byte[] result = md5.ComputeHash (data);
String strReturn = String.Empty;
for (int i = 0; i < result.Length; i++)
strReturn += result[i].ToString ("x").PadLeft (2,'0');
return strReturn;
}
//发送请求 url 是发送的地址,sendMsg为发送数据的内容
public static void sendToRetUrl (string url,string sendMsg)
{
//签名串
MD5 md5 = new MD5CryptoServiceProvider ();
byte[] data = System.Text.Encoding.UTF8.GetBytes ("cen" + sendMsg);
byte[] result = md5.ComputeHash (data);
String strReturn = String.Empty;
for (int i = 0; i < result.Length; i++)
strReturn += result[i].ToString ("x").PadLeft (2,'0');
// sendMsg = HttpUtility.UrlEncode (sendMsg + "&SignMsg=" + strReturn,Encoding.GetEncoding ("utf-8"));
url = url + sendMsg + "&SignMsg=" + strReturn;
Console.WriteLine ("-------"+url);
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create (url);
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
request.Method = "GET";
request.CachePolicy = new System.Net.Cache.RequestCachePolicy (System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
request.Headers.Add ("Pragma","No-cache");
request.Accept = "*/*";
request.KeepAlive = true;
request.ServicePoint.Expect100Continue = false;
request.Timeout = 120000;
request.ContentLength = 0;
System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse ();
Stream resStream = response.GetResponseStream ();
byte[] byteResponse = new byte[response.ContentLength];
resStream.Read (byteResponse,0,(int)response.ContentLength);
string strResponse = Encoding.Default.GetString (byteResponse);
Console.WriteLine ("-------strResponse-----" + strResponse);
response.Close ();
resStream.Close ();
}
}
}