如何从c#通过localhost发布json并获取php中的数据?

时间:2017-03-29 16:18:26

标签: c# php json

我试图用一个非常简单的UI来做一个简单的程序。

只需按一下c#windows形式的按钮,当我按下按钮时,它会将一个简单的数组编码为Json并将其上传到http://localhost,然后以PHP格式获取json数据。

这是我现在在c#

中的代码
private void button_Click(object sender, RoutedEventArgs e)
{
    var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:8080/SemesterProject/index.php");
    httpWebRequest.ContentType = "application/json";
    httpWebRequest.Method = "POST";

    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
        string json = new JavaScriptSerializer().Serialize(new
        {
            user = "Foo",
            password = "Baz"
        });

        streamWriter.Write(json);
        Console.WriteLine("Console.WriteLine(json);");
        Console.WriteLine(json);

    }


    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        var result = streamReader.ReadToEnd();
        Console.WriteLine("Console.WriteLine(result);");
        Console.WriteLine(result);

    }
}

这是我在PHP中的代码:

<?php
$post= file_get_contents("php://input");
$decodedjson=json_decode($post,true);
var_dump($decodedjson);

?>

在PHP输出我得到        &#39; NULL&#39; 在c#输出中我得到了

Console.WriteLine(json);
{"user":"Foo","password":"Baz"}
Console.WriteLine(result);
array(2) {
  ["user"]=>
  string(3) "Foo"
  ["password"]=>
  string(3) "Baz"
}

在此之后我需要将数据从PHP发布到phpMyAdmin数据库

1 个答案:

答案 0 :(得分:0)

尝试简单的方法:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections.Specialized;
using System.Net;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
    public Form1()
        {
        InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

        using (var client = new WebClient())
            {
            var postData = new NameValueCollection();
            postData["user"] = "Foo";
            postData["password"] = "Baz";
            var response = client.UploadValues("http://localhost/xxx.php", postData);
            var data = Encoding.Default.GetString(response);
            // Console.WriteLine("Data from server: " + data);
            MessageBox.Show(data);
            }

        }
    }
}

// php file xxx.php

<?php
echo json_encode($_POST);
?>

在你的留言框中将显示json string