Reputation: 71
Im sending data to local website using c# console application. Function that sends data is:
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 and NameValueCollection are correct. but I cant receive anything on the website. website code is:
System.IO.StreamReader reader = new System.IO.StreamReader(HttpContext.Current.Request.InputStream);
string requestFromPost = reader.ReadToEnd();
Response.Write(requestFromPost);
I'm new to asp.net. What am I missing?
Upvotes: 1
Views: 380
Reputation: 88044
Try this.
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;
You probably want to wrap most of the above in a try..catch
. If the post fails then it's going to throw an exception.
On the receiving end, it's a little easier. You can do things like:
String val = Request.QueryString["myparam"];
or just iterate through the query string collection.
Upvotes: 1