如何使用 JSON 和 C# 正确发布到 php Web 服务

本文关键字:php Web 服务 JSON 何使用 | 更新日期: 2023-09-27 17:57:20

我正在尝试联系一个简单的登录 Web 服务,该服务将确定 JSON 请求是否成功。 目前,在 C# 程序中,我收到一条错误消息,指出缺少 JSON 参数。在 Web 浏览器中请求的正确 URL 是:

https://devcloud.fulgentcorp.com/bifrost/ws.php?json=[{"action":"login"},{"login":"demouser"},{"password":"xxxx"},{"checksum":"xxxx"}]

我现在在 C# 中实现的代码是:

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;
namespace request
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://devcloud.fulgentcorp.com/bifrost/ws.php?");
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "POST";
            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                string json = new JavaScriptSerializer().Serialize(new
                {
                    action = "login",
                    login = "demouser",
                    password = "xxxx",
                    checksum = "xxxx"
                });
                Console.WriteLine ("'n'n"+json+"'n'n"); 
                streamWriter.Write(json);
            }
            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                Console.WriteLine (result); 
            } 

        }
    }
}

如何使用 JSON 和 C# 正确发布到 php Web 服务

看起来示例 URL 正在将 JSON 作为查询字符串传递 - 这是一个简单的 GET 请求。

您正在尝试 POST JSON——这是一种在查询字符串中传递 JSON 的更好方法——即由于长度限制,以及需要转义空格等简单字符。但它不会像您的示例 URL 那样工作。

如果您能够修改服务器,我建议修改 PHP 以使用 $_REQUEST['action'] 来使用数据,以及以下 C# 代码:

Public static void Main (string[] args)
{
    using (var client = new WebClient())
    {
            var Parameters = new NameValueCollection {
            {action = "login"},
            {login = "demouser"},
            {password = "xxxx"},
            {checksum = "xxxx"}
            httpResponse = client.UploadValues( "https://devcloud.fulgentcorp.com/bifrost/ws.php", Parameters);
            Console.WriteLine (httpResponse);
    }
}

如果必须将 JSON 作为查询字符串传递,则可以使用 UriBuilder 安全地创建完整的 URL + 查询字符串,然后发出 GET 请求 - 无需 POST。