您的位置:首页 > 其它

EXAMPLE of parsing GET and POST

2011-08-23 02:38 218 查看
public Dictionary<String, String> parseRequest(String requestString)
{
// deal with GET and POST
Dictionary<String, String> dic = new Dictionary<string, string>();

String[] tmp = requestString.Split(' ');

String head = tmp[0].ToUpper();

if(head.Equals("GET"))
{
// all request should be in the url, deal with parameters
try
{
String[] reqstr = tmp[1].Split('?');
String[] parameters = reqstr[1].Split('&');

foreach (String param in parameters)
{
String[] sparam = param.Split('=');
dic.Add(sparam[0], sparam[1]);
}
}
catch (Exception ex)
{
return null;
}
}
else if (head.Equals("POST"))
{
String[] reqstr = requestString.Split('\n');

// locate Post content line
int line = 0;
for (int i = 0; i < reqstr.Length; i++)
{
if (reqstr[i].Length <= 1)
{
line = i;
break;
}
}

// prepare post content
try
{
String postContent = reqstr[i + 1];
String[] parameters = postContent.Split('&');

foreach (String param in parameters)
{
String[] sparam = param.Split('=');
dic.Add(sparam[0], sparam[1]);
}

}
catch (Exception ex)
{
return null;
}
}
else
{
// check null if nothing parsed.
dic = null;
}

return dic;
}

}
}


=========================

using System.Collections.Generic;

using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
Dictionary<string, int> d = new Dictionary<string, int>();
d.Add("apple", 1);
d.Add("windows", 5);

// See if Dictionary contains this string
if (d.ContainsKey("apple")) // True
{
int v = d["apple"];
Console.WriteLine(v);
}

// See if Dictionary contains this string
if (d.ContainsKey("acorn"))
{
Console.WriteLine(false); // Nope
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: