2015-06-21 126 views
0

我想聯繫一個簡單的登錄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); 
      } 


     } 
    } 
} 

回答

1

它看起來像樣品的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