I am new to C#. I tried all solutions to other questions and still i can't find what is wrong. My code is common in other answers but it seems to never send anything. I have tried in my own server and the company i'm working for server. I know this kind of answer has been answered many times before, but maybe i am missing something like others so this might be useful to someone besides me.
C# code:
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 script in my server:
<?php
$json = null;
if (isset($_POST['user_token']))
{
$json = $_POST['user_token'];
echo "user";
}
?>
You have to decode your json post in PHP. Try using this:
$json = json_decode($_POST);
if (isset($json['user_token']) {
$userToken = $json['user_token'];
}
If you want $_POST
to understand your data, it has to be sent as form-encoded key=value&key2=value2
, not as JSON.
If you want to post JSON, you need to decode it on server side:
$post = (array)json_decode(file_get_contents("php://input"));
if (isset($post['user_token'])) {
// ...
}
You can replace file_get_contents("php://input")
with $HTTP_RAW_POST_DATA
, but its availability depends on configuration.
PS streamWriter.Flush()
call is redundant.
将您的json解码为数组:
$json = json_decode($_POST, true);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.