【问题标题】:How can i receive json data on PHP file?如何接收 PHP 文件中的 json 数据?
【发布时间】:2020-08-10 05:11:30
【问题描述】:

我是 Xamarin 和 C# 的新手,我想从我的应用程序中将书籍名称和作者插入 MySql 数据库,所以我创建了名为 BooksInsert.cs 的类:

using System;
using System.Collections.Generic;
using System.Text;

namespace NewTest.Model
{
    class BooksInsert
    {
        public string book_name { get; set; }
        public string book_auther { get; set; }
    }
}

然后是另一个名称为 WebHelper.cs 的类,用于 GET 和 POST :

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Linq;
using System.Net;

namespace NewTest.Model
{
    class WebHelper
    {
        public string Post(Uri url, string value)
        {
            var request = HttpWebRequest.Create(url);
            var byteData = Encoding.ASCII.GetBytes(value);
            request.ContentType = "application/json";
            request.Method = "POST";

            try
            {
                using (var stream = request.GetRequestStream())
                {
                    stream.Write(byteData, 0, byteData.Length);
                }
                var response = (HttpWebResponse)request.GetResponse();
                var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

                return responseString;
            }
            catch (WebException)
            {
                return null;
            }
        }

        public string Get(Uri url)
        {
            var request = HttpWebRequest.Create(url);
            request.ContentType = "application/json";
            request.Method = "GET";

            try
            {
                var response = (HttpWebResponse)request.GetResponse();
                var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

                return responseString;
            }
            catch (WebException)
            {
                return null;
            }
        }

    }
}

在添加页面 NewBookPage.xaml 我有这个内容:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="NewTest.NewBookPage">

    <ContentPage.Content>
        <StackLayout>
            <Entry x:Name="b_name" Placeholder="Name of Book"/>
            <Entry x:Name="b_auther" Placeholder="auther of Book"/>
            <Button Text="Save"
                    Clicked="Button_Clicked"/>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

和 NewBookPage.xaml.cs :

using NewTest.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;


namespace NewTest
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class NewBookPage : ContentPage
    {
        public NewBookPage()
        {
            InitializeComponent();
        }

        private void Button_Clicked(object sender, EventArgs e)
        {
            WebHelper webHelper = new WebHelper();

            BooksInsert item = new BooksInsert();
            item.book_name= b_name.Text;
            item.book_auther = b_auther.Text;


            string request = JsonConvert.SerializeObject(item);

            Uri url = new Uri(string.Format("localhost/API/insert.php"));

            string response = webHelper.Post(url, request);

            if (response != null)
            {
                //Handle your reponse here
            }
            else
            {
                //No Response from the server

            }
        }
    }
}

现在我不知道如何继续将 json 文件发送到 insert.php 文件以及在 insert.php 中如何接收 json 数据,谁能帮助我?

【问题讨论】:

  • 您不需要将 JSON 文件 发送到 PHP 脚本。如果这些 PHP 脚本以 JSON 形式接收有效负载,则只需对有效负载进行编码即可。我好像你已经在这里做了:string request = JsonConvert.SerializeObject(item);NewBookPage.xaml.cs。你测试过你的程序吗?您能否提供更多数据,例如请求响应和错误?你知道insert.php API 吗?
  • @Andre 我测试了一下,说不支持uri格式,那我怎么把数据插入MySql数据库
  • 这个 PHP 脚本是否在本地网络服务器中运行?你有没有试过把http://放在URL前面,所以它变成http://localhost/API/insert.php?另外,我会检查它在哪个端口运行,通常是端口80
  • http:// url 没有问题,但现在我只需要如何在 insert.php 文件中获取数据
  • @AndreRavazzi 我在 http:// 中检查过,在数据库中插入了新行但没有数据,insert.php 没有从应用程序接收数据,我如何在 insert.php 中接收数据

标签: c# php mysql json


【解决方案1】:

WebHelper.cs 中的Post 方法期望将Uri 实体作为第一个参数传递给HttpWebRequest.Create。但正如documentation 所述,它似乎期望string 作为参数,而不是Uri 类。此外,HttpWebRequest 已过时,不应用于新开发。 MS 声明您应该改用HttpClient

尝试使用 WebRequest.Create 代替 MS 的本教程:https://docs.microsoft.com/en-us/dotnet/framework/network-programming/how-to-request-data-using-the-webrequest-class

WebRequest request = WebRequest.Create("http://localhost/API/insert.php");

如果更改Post方法签名,则不需要使用NewBookPage.xaml.cs中的Uri类,只需将URI作为字符串发送到Post即可。

【讨论】:

    【解决方案2】:

    我不知道它是如何正确的,但我尝试了将数据插入 MySql 数据库的简单方法,我只是做了这个 NewBookPage.xaml :

    <?xml version="1.0" encoding="utf-8" ?>
    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 xmlns:d="http://xamarin.com/schemas/2014/forms/design"
                 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                 mc:Ignorable="d"
                 x:Class="NewTest.NewBookPage">
    
        <ContentPage.Content>
            <StackLayout>
                <Entry x:Name="b_name" Placeholder="Name of Book"/>
                <Entry x:Name="b_auther" Placeholder="auther of Book"/>
                <Button Text="Save"
                        Clicked="Button_Clicked"/>
                <WebView x:Name="webView"
                    WidthRequest="1000"
                    HeightRequest="500"/>
            </StackLayout>
        </ContentPage.Content>
    </ContentPage>
    

    NewBookPage.xaml.cs:

    using NewTest.Model;
    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    using Xamarin.Forms;
    using Xamarin.Forms.Xaml;
    
    
    namespace NewTest
    {
        [XamlCompilation(XamlCompilationOptions.Compile)]
        public partial class NewBookPage : ContentPage
        {
            public NewBookPage()
            {
                InitializeComponent();
            }
    
            private void Button_Clicked(object sender, EventArgs e)
            {
                webView.Source = " https://Mywebsite/insert.php?bn=" + b_name.Text + "&ba=" + b_auther.Text;   
            }
        }
    }
    

    插入.php

    $bname=$_GET['bn'];
    $bauthor=$_GET['ba'];
    $query = "INSERT INTO books  VALUES ('','$bname','$bauthor')";
    mysqli_query($berikane,$query);
    

    数据插入正确,这个解决方案怎么可能?

    【讨论】:

    • 您的 insert.php 不接收 JSON,但接收 URL 参数。在构建消费者之前,您应该确认后端的 API。
    【解决方案3】:

    最后,我将 Xamarin 中的 Post 数据发送到 PHP 文件,并将其作为 post 值接收:

     private  void Button_Clicked(object sender, EventArgs e)
            {
    
                using (var client = new WebClient())
                {
                    var values = new NameValueCollection();
                    values["book_name"] = b_name.Text;
                    values["book_auther"] = b_auther.Text;
    
                    var response = client.UploadValues("https://MyWeb/insert.php", values);
    
                    var responseString = Encoding.Default.GetString(response);
    
                    if (response != null)
                    {
                        DisplayAlert("Success" ,"Data Inserted Successfully" ,"OK");
                    }
                }
    
            } 
    

    【讨论】:

      猜你喜欢
      • 2017-09-25
      • 1970-01-01
      • 1970-01-01
      • 2022-01-02
      • 2019-04-22
      • 1970-01-01
      • 1970-01-01
      • 2019-09-10
      • 1970-01-01
      相关资源
      最近更新 更多