Parse POST parameters from HttpListener

自作多情 提交于 2020-01-11 09:24:19

问题


Let's say i have HttpListener. It listen some port and ip. When i send POST request it catch it. How can i parse POST parameters from HttpListenerRequest?

HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;

if ( request.HttpMethod == "POST" )
{
  // Here i can read all parameters in string but how to parse each one i don't know                                            
}

回答1:


The POST body (read from the InputStream on the HttpListenerRequest) is parsed using whatever mechanism you choose to encode the POST data with.

For example, you could be sending JSON using JSON.stringify calls on a JavaScript object in a browser. In that case you could use the JSON deserializer in .Net or JSON.Net.

Or, you might choose to send XML, or CSV, or something else entirely.

Hope that helps - Harold




回答2:


I ran into this issue a few hours ago and banged out this answer hoping it helps someone when parsing out POST data

//using System.Web and Add a Reference to System.Web
Dictionary<string, string> postParams = new Dictionary<string, string>();
string[] rawParams = rawData.Split('&');
foreach (string param in rawParams)
{
    string[] kvPair = param.Split('=');
    string key = kvPair[0];
    string value = HttpUtility.UrlDecode(kvPair[1]);
    postParams.Add(key, value);
}

//Usage
Console.WriteLine("Hello " + postParams["username"]);


来源:https://stackoverflow.com/questions/19031438/parse-post-parameters-from-httplistener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!