我使用c#console应用程序将数据发送到本地网站。发送数据的功能是:
public static HttpWebRequest GetRequest(String url, NameValueCollection nameValueCollection)
{
// Here we convert the nameValueCollection to POST data.
// This will only work if nameValueCollection contains some items.
var parameters = new StringBuilder();
foreach (string key in nameValueCollection.Keys)
{
parameters.AppendFormat("{0}={1}&",
HttpUtility.UrlEncode(key),
HttpUtility.UrlEncode(nameValueCollection[key]));
}
parameters.Length -= 1;
// Here we create the request and write the POST data to it.
var request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "POST";
using (var writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(parameters.ToString());
}
return request;
}
url和NameValueCollection是正确的。 但我无法在网站上收到任何东西。 网站代码是:
System.IO.StreamReader reader = new System.IO.StreamReader(HttpContext.Current.Request.InputStream);
string requestFromPost = reader.ReadToEnd();
Response.Write(requestFromPost);
我是asp.net的新手。我错过了什么?
答案 0 :(得分:1)
试试这个。
var parameters = new StringBuilder();
foreach (string key in nameValueCollection.Keys)
{
parameters.AppendFormat("{0}={1}&",
HttpUtility.UrlEncode(key),
HttpUtility.UrlEncode(nameValueCollection[key]));
}
parameters.Length -= 1;
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// Every so often I've seen weird issues if the user agent isn't set
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
// encode the data for transmission
byte[] bytedata = Encoding.UTF8.GetBytes(parameters.ToString());
// tell the other side how much data is coming
request.ContentLength = bytedata.Length;
using (Stream writer = request.GetRequestStream())
{
writer.Write(bytedata, 0, bytedata.Length);
}
String result = String.Empty;
using (var response = (HttpWebResponse)request.GetResponse()) {
using(StreamReader reader = new StreamReader(response.GetResponseStream())) {
result = reader.ReadToEnd(); // gets the response from the server
// output this or at least look at it.
// generally you want to send a success or failure message back.
}
}
// not sure why you were returning the request object.
// you really just want to pass the result back from your method
return result;
您可能希望将上述大部分内容包含在try..catch
中。如果帖子失败则会抛出异常。
在接收端,它更容易一些。你可以这样做:
String val = Request.QueryString["myparam"];
或只是遍历查询字符串集合。