如何通过本地主机从 c# 发布 json 并以 php 格式获取数据



我正在尝试用非常简单的UI做一个简单的程序。

只是一个 c# 窗口表单中的一个按钮,当我按下按钮时,它会将一个简单的数组编码为 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 输出我得到 "空"在 C# 输出中,我得到

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

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

尝试简单的方法:

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 文件 xxx.php

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

在您的消息框中将播放 json 字符串

最新更新