4

好的,所以我有我创建的 ac# 控制台源代码,但它不能按我想要的方式工作。

我需要将数据发布到一个 URL,就像我要在浏览器中输入它一样。

url with data = localhost/test.php?DGURL=DGURL&DGUSER=DGUSER&DGPASS=DGPASS

这是我的 c# 脚本,它没有按照我想要的方式执行它我希望它像上面那样输入数据一样发布数据。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Collections.Specialized;
using System.Net;
using System.IO;


namespace ConsoleApplication1
{
  class Program
  {
     static void Main(string[] args)
     {
        string URL = "http://localhost/test.php";
        WebClient webClient = new WebClient();

        NameValueCollection formData = new NameValueCollection();
        formData["DGURL"] = "DGURL";
        formData["DGUSER"] = "DGUSER";
        formData["DGPASS"] = "DGPASS";

        byte[] responseBytes = webClient.UploadValues(URL, "POST", formData);
        string responsefromserver = Encoding.UTF8.GetString(responseBytes);
        Console.WriteLine(responsefromserver);
        webClient.Dispose();
    }
  }
}

我还在 c# 中尝试了另一种方法,现在也可以使用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Collections.Specialized;
using System.Net;
using System.IO;


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string URI = "http://localhost/test.php";
            string myParameters = "DGURL=value1&DGUSER=value2&DGPASS=value3";

            using (WebClient wc = new WebClient())
            {
                wc.Headers[HttpRequestHeader.ContentType] = "text/html";
                string HtmlResult = wc.UploadString(URI, myParameters);
                System.Threading.Thread.Sleep(500000000);
            }
        }
    }
}

几天来,我一直在试图想办法在我的 c# 控制台中做到这一点

4

2 回答 2

3

由于您似乎想要的是带有查询字符串而不是 POST 的 GET 请求,因此您应该这样做。

static void Main(string[] args)
{
    var dgurl = "DGURL", user="DGUSER", pass="DGPASS";
    var url = string.Format("http://localhost/test.php?DGURL={0}&DGUSER={1}&DGPASS=DGPASS", dgurl, user, pass);
    using(var webClient = new WebClient()) 
    {
        var response = webClient.DownloadString(url);
        Console.WriteLine(response);
    }
}

我还将您包装WebClient在一个using- 语句中,因此您不必担心自己处理它,即使它会在下载字符串时引发异常。

要考虑的另一件事是,您可能希望使用WebUtility.UrlEncode对查询字符串中的参数进行 url 编码,以确保它不包含无效字符。

于 2013-10-05T13:18:52.180 回答
0

如何在 C# 中使用 WebClient 将数据发布到 URL:https ://stackoverflow.com/a/5401597/2832321

另请注意,如果您发布参数,您的参数将不会出现在 URL 中。请参阅:https ://stackoverflow.com/a/3477374/2832321

于 2013-10-04T20:24:27.677 回答