How to simulate HTTP POST programmatically in ASP.

2020-02-04 05:54发布

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.

5条回答
霸刀☆藐视天下
2楼-- · 2020-02-04 06:13

I asked this question in the past here:

POST a HTML Form programmatically?

I was directed to the following link which worked great for me!:

WebClient.UploadValues

查看更多
看我几分像从前
3楼-- · 2020-02-04 06:16

I don't think it is easy to do what you want, but there may be an acceptable workaround. Here are some ideas for workarounds:

  • Return javascript to the browser along with the form you want to post, and have the javascript do the post for you. This isn't secure, though.
  • If the destination page is under your control, pass data through HttpContext.Current.Items, call Transfer, and have the destination page recognize that special case and handle it. One advantage to using HttpContext.Current.Items is that it is cleared automatically at the end of a request, unlike Session state.
  • HttpServerUtility.Execute can be useful if you want to embed results from another page into the current page. It does not let you set the form post data or the URL Request parameters.
  • Run the HttpWebRequest as described in the other answers, and use Response.Write to return that as the response from your web page. You may also need to supply the users authentication credentials and cookies. See HttpWebRequest.Credentials and HttpWebRequest.CookieContainer.
  • If you can modify the destination page so that it will display the same information if it is re-requested, you can do the HttpWebRequest, and follow it with a Redirect for the browser.
  • Refactor the code so that either page can generate the same output (eg: using a shared UserControl or custom WebControl).
  • Page scraping can be useful if the destination page is on another site. Make the request, scrape the results, and show the results on your own page.
查看更多
地球回转人心会变
4楼-- · 2020-02-04 06:24

You need HttpWebRequest class.

查看更多
祖国的老花朵
5楼-- · 2020-02-04 06:25

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();
}
查看更多
ゆ 、 Hurt°
6楼-- · 2020-02-04 06:25

Something like this?

    public string DoFormPost(string Target, string PostData)
    {
        //Make a request            
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Target);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.AllowAutoRedirect = false;

        //Put the post data into the request
        byte[] data = (new ASCIIEncoding()).GetBytes(PostData);
        request.ContentLength = data.Length;
        Stream reqStream = request.GetRequestStream();
        reqStream.Write(data, 0, data.Length);
        reqStream.Close();

        //Get response
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        //Output response to a string            
        String result = "";
        using (Stream responseStream = response.GetResponseStream())
        {
            using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
                reader.Close();
            }
            return result;
        }
    }
查看更多
登录 后发表回答