Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

forms - How to simulate HTTP POST programmatically in ASP.NET?

I need to simulate an HTTP POST programmatically, i.e., I need to generate a Request with some POST variables and then send it to a page.

To clarify, I need to simulate the behaviour of a regular POST, not do the whole thing programmatically. So basically I need to fill in a Request in the same way it would be filled if a form POST was happening, and then send the browser to the page that expects the POST.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is one way to do it.

You send this method the url and the name/value parameters in the form of a NameValueCollection. The method makes a Http Post on the endpoint and returns the response as a string.

Of course depending on what/why you're doing this and how many times this method will be called, there maybe other alternatives. But until you provide more information on your specific needs, this method is good enough.

The method below uses Tasks (.NET 4.0) and the async methods so it will be faster then a synchronous method like the next code listing if you're making multiple calls in a loop for example.

static string GetWebResponse(string url, NameValueCollection parameters)
{
  var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
  httpWebRequest.ContentType = "application/x-www-form-urlencoded";
  httpWebRequest.Method = "POST";

  var sb = new StringBuilder();
  foreach (var key in parameters.AllKeys)
    sb.Append(key + "=" + parameters[key] + "&");
  sb.Length = sb.Length - 1;

  byte[] requestBytes = Encoding.UTF8.GetBytes(sb.ToString());
  httpWebRequest.ContentLength = requestBytes.Length;

  using (var requestStream = httpWebRequest.GetRequestStream())
  {
    requestStream.Write(requestBytes, 0, requestBytes.Length);
    requestStream.Close();
  }

  Task<WebResponse> responseTask = Task.Factory.FromAsync<WebResponse>(httpWebRequest.BeginGetResponse, httpWebRequest.EndGetResponse, null);
  using (var responseStream = responseTask.Result.GetResponseStream())
  {
    var reader = new StreamReader(responseStream);
    return reader.ReadToEnd();
  }
}

you could also use WebClient (it's bit simpler). This method expects the post parameters as a string in the form

name1=value1&name2=value2&name3=value3

etc. So if you use this method be sure to pass in your parameters as such or modify the implementation to be like the code above.

static string HttpPost(string url, string Parameters) 
{
   var req = System.Net.WebRequest.Create(url);       

   req.ContentType = "application/x-www-form-urlencoded";
   req.Method = "POST";
   byte[] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
   req.ContentLength = bytes.Length;
   System.IO.Stream os = req.GetRequestStream ();
   os.Write (bytes, 0, bytes.Length);
   os.Close ();
   System.Net.WebResponse resp = req.GetResponse();
   if (resp== null)
     return null;
   var sr = new StreamReader(resp.GetResponseStream());
   return sr.ReadToEnd().Trim();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...