HttpWebRequest virtual button click

2019-06-25 12:25发布

问题:

I have my html-php web page with form, inputs and sumbit button. With html request I\m trying to fill some fields and press a button, but I can't. Here is C# code:

public static string PostData(string data)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/request.php"); //http://businesslist.com/search/clients/?m=userspace&d=addclassified
    request.Method = "POST";
    request.AllowAutoRedirect = true;
    request.ContentType = "application/x-www-form-urlencoded";
    byte[] EncodedPostParams = Encoding.UTF8.GetBytes(data);
    request.ContentLength = EncodedPostParams.Length;
    request.GetRequestStream().Write(EncodedPostParams, 0, EncodedPostParams.Length);
    request.GetRequestStream().Close();
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    string str = new StreamReader(response.GetResponseStream(), Encoding.UTF8).ReadToEnd();
    return str;
}
static void Main(string[] args)
{
    string data = PostData("name=" + HttpUtility.UrlEncode("lol") + "&btn=Clicked");

    Console.WriteLine(data);
    Console.ReadLine();
}

and 2 php files: request.php

<html>
<head>
<title>HTTP Request</title>
</head>
<body>
<form action ="http://localhost/response.php" method ="POST">
<input type="text" name="name">
<input type="password" name="pass">
<select name="country">
<option value="-1" selected="selected">Select State/Country</option>
<option value="82">Select 1</option>
<option value="83">Select 2</option>
</select>
<input type="submit" name="btn">
</form>
</body>
</html>

response.php

<?php
   $data = $_POST["name"];
   echo $data;
?>

Here is link to my site

So, how I can press this button?

回答1:

I've tried this in LINQPad and it worked:

void Main()
{
    var request = (HttpWebRequest)WebRequest.Create("http://128.75.49.209/response.php");
    request.Method = WebRequestMethods.Http.Post;
    request.ContentType = "application/x-www-form-urlencoded";
    using (var stream = request.GetRequestStream())
    {
        var buffer = Encoding.UTF8.GetBytes("name=asd&pass=asd&country=82&btn=Submit+Query");
        stream.Write(buffer,0,buffer.Length);
    }
    var response = (HttpWebResponse)request.GetResponse();
    string result = String.Empty;
    using (var reader = new StreamReader( response.GetResponseStream()))
    {
        result = reader.ReadToEnd();
    }
    Console.WriteLine(result);
}

The problem is that you used request.php instead of response.php in your code.