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

问题描述:

我想联系一个简单的登录Web服务,将确定是否JSON请求是否成功。目前,在C#程序中,我产生了一个错误,指出缺少JSON参数。正确的URL在Web浏览器的要求是:如何正确发布到php web服务使用JSON和C#

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); 
      } 


     } 
    } 
} 

它看起来像样品的URL传递JSON作为查询字符串 - 这是一个简单的GET请求。

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

如果你可以修改我建议修改PHP使用$ _REQUEST [“行动”]消耗数据,以及下面的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。

+0

啊好吧谢谢这就是它。我查找了GET请求,并从微软找到了一个很好的样例。再次感谢 – MeesterMarcus

+0

没有probs。谢谢你的勾号。 – Patrick