2014-02-21 51 views
1

我是新來的C#。我嘗試瞭解其他問題的所有解決方案,但仍無法找到問題所在。我的代碼在其他答案中很常見,但它似乎永遠不會發送任何內容。我嘗試過在自己的服務器和我爲服務器工作的公司。我知道這種答案已經回答過很多次了,但也許我的思念像其他人那麼這可能是除了我有用的人。

C#代碼:

 var buttonSaveClicked = new MouseEventHandler((o, a) => 
     { 
      var user_token = this.textApiKey.Text; 

      if (user_token.Length == 0) MessageBox.Show("API Key cannot be empty!", "API Key Error", MessageBoxButtons.OK, MessageBoxIcon.None); 

      var httpWebRequest = (HttpWebRequest) WebRequest.Create("http://localhost/networksWindows.php"); 
      httpWebRequest.ContentType = "application/json; charset=utf-8"; 
      httpWebRequest.Method = "POST"; 

      using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) 
      { 
       string json = "{\"user_token\": \"batatas\", \"bata\": \"cook\"}"; 

       System.Diagnostics.Debug.WriteLine(json); 

       streamWriter.Write(json); 
       streamWriter.Flush(); 
      } 

      var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); 
      using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) 
      { 
       var result = streamReader.ReadToEnd(); 
       System.Diagnostics.Debug.WriteLine(result); 
       User user = JsonConvert.DeserializeObject<User>(result); 

       if (user.status == "error") MessageBox.Show("Invalid API Key. Please make sure you have generated a API key and insert it correctly.", "API Key Error", MessageBoxButtons.OK, MessageBoxIcon.None); 
       else if (user.status == "success") 
       { 
        System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadProc)); 

        t.Start(); 

        this.Close(); 
       } 
      } 

     }); 

PHP腳本在我的服務器:

<?php 

$json = null; 

if (isset($_POST['user_token'])) 
{ 
$json = $_POST['user_token']; 

echo "user"; 
} 

?> 
+0

'$ _POST'不解析JSON。 – SLaks

回答

1

如果你想$_POST瞭解您的數據,它必須被作爲表單編碼key=value&key2=value2,而不是JSON。

如果您想發表JSON,你需要把它在服務器端進行解碼:

$post = (array)json_decode(file_get_contents("php://input")); 
if (isset($post['user_token'])) { 
    // ... 
} 

您可以$HTTP_RAW_POST_DATA取代file_get_contents("php://input"),但其可用性取決於配置。

P.S. streamWriter.Flush()呼叫是多餘的。

+0

這是由於C#?因爲我使用Java發送JSON,並讓我顯示的代碼接收JSON發佈請求,並且它工作正常。 – mobilepotato7

+0

您可能使用過不同的方法來發送Java數據,因爲它不依賴於語言。 – Athari

+0

我看:)感謝您的回答。我將嘗試找到一種使用C#進行表單編碼發送的方式。 – mobilepotato7

1

你來解碼你的PHP JSON職位。 嘗試使用這樣的:

$json = json_decode($_POST); 
if (isset($json['user_token']) { 
    $userToken = $json['user_token']; 
} 
+0

您的代碼將無法正常工作。 1.'json_decode'返回'stdClass',不'array'。 2.'$ _POST'不包含原始的發佈數據。 – Athari

0

解碼你的JSON作爲數組:

$json = json_decode($_POST, true);