简体   繁体   中英

How can i receive json data on PHP file?

I am new in Xamarin and C#,I want from my app to insert Books name and author to MySql database,so I made class with name 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; }
    }
}

then another class with name WebHelper.cs for GET and 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;
            }
        }

    }
}

in the adding page NewBookPage.xaml I have this contents:

<?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>

and 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

            }
        }
    }
}

Now i don't know how to continue send json file to insert.php file and in insert.php how can i receive json data,can any one help me?

Your Post method in WebHelper.cs is expecting an Uri entity as the first argument to be passed to HttpWebRequest.Create . But as the documentation states, it seems to expect a string as parameter, not an Uri class. Besides HttpWebRequest is obsolete and should not be used for new developments. MS states you should use HttpClient instead.

Try using WebRequest.Create instead as in this tutorial from 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");

If you change the Post method signature, then you don't need to use the Uri class in NewBookPage.xaml.cs , just send the URI as string to Post .

I don't know how it is correct,but i tried simple way to insert data's to MySql database,I just did this 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;   
        }
    }
}

insert.php

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

data inserted correctly,how is this solution possible?

Finally I have sent Post data from Xamarin to PHP file and received it as post value:

 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");
                }
            }

        } 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM