首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用JSON和C#正确地向php服务发布

如何使用JSON和C#正确地向php服务发布
EN

Stack Overflow用户
提问于 2015-06-21 22:21:13
回答 1查看 619关注 0票数 1

我试图联系一个简单的登录web服务,以确定JSON请求是否成功。目前,在C#程序中,我遇到了一个错误,说缺少一个JSON参数。在web浏览器中请求的正确URL是:

代码语言:javascript
复制
https://devcloud.fulgentcorp.com/bifrost/ws.php?json=[{"action":"login"},{"login":"demouser"},{"password":"xxxx"},{"checksum":"xxxx"}]

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

代码语言:javascript
复制
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); 
            } 


        }
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-06-22 02:42:17

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

您正在尝试发布JSON --这是在查询字符串中传递JSON的一种更好的方法--也就是说,由于长度限制和需要转义简单字符(例如空格)。但是它不会像您的示例URL那样工作。

如果您能够修改服务器,我建议修改PHP以便使用$_ C#‘’action‘来使用数据,并使用以下C#代码:

代码语言:javascript
复制
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请求--无需发布。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30969910

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档