ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

c#将数据发送到php url

2019-06-29 10:18:33  阅读:252  来源: 互联网

标签:php c 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#控制台中找到一种方法

解决方法:

既然你想要的是一个带有查询字符串而不是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编码,以确保它不包含无效字符.

标签:php,c,postdata
来源: https://codeday.me/bug/20190629/1325107.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有