HttpWebRequest 虚拟按钮单击

本文关键字:单击 按钮 虚拟 HttpWebRequest | 更新日期: 2023-09-27 18:34:09

我有我的html-php网页,上面有表单,输入和sumbit按钮。使用 html 请求,我''正在尝试填写一些字段并按下按钮,但我不能。下面是 C# 代码:

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();
}

和 2 个 PHP 文件:请求.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>

响应.php

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

这是指向我网站的链接

那么,我该如何按下此按钮?

HttpWebRequest 虚拟按钮单击

我已经在 LINQPad 中尝试过这个并且它起作用了:

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);
}

问题是您在代码中使用了request.php而不是response.php