c#将数据发送到php url

时间:2013-10-04 20:14:28

标签: c# php postdata

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

我需要将数据发布到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#控制台中找到一种方法来实现这一目标

2 个答案:

答案 0 :(得分:3)

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

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编码,以确保它不包含无效的字符。

答案 1 :(得分:0)

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

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