2013-10-04 54 views
2

好吧,所以我有一个c#控制台源代码,我已经创建,但它不工作,我想如何。c#发送数据到php url

我需要将数据发布到一个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#中triead另一种方法这样做现在的工作或者

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#控制台现在

+0

问题是什么?怎么了? – SLaks

+0

我有一个php脚本,等待的url帖子,然后将数据添加到MySQL,如果我manualy访问该数据添加的url,但它不会添加当我运行此代码 – user2847609

+1

为什么我们是黄色的 – tnw

回答

2

由于您似乎想要的是具有querystrings而不是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); 
    } 
} 

我也是在using语句来包裹你的WebClient,所以你不必担心自己即使处置它,如果下载的字符串时,它会抛出异常。

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