简体   繁体   English

如何从asp.net到php接收JSON POST数据?

[英]How to receive JSON POST data from asp.net to php?

I am trying to build an API for my php website and the API is using from asp.net site to insert data to my php MySql site. 我正在尝试为我的php网站构建一个API,并且该API正在使用来自asp.net站点的数据将数据插入到我的php MySql站点。 I have checked this with the postman and it is working. 我已经与邮递员检查过,它正在工作。 But while accessing from asp.net it is just getting the null values only. 但是当从asp.net访问时,它仅获得空值。 The data posted from using JSON from asp.net is 从asp.net使用JSON发布的数据是

JSON POST array from asp.net 来自asp.net的 JSON POST数组

    string reqJson = "{\"user_id\":\"" + user_id + "\",\"name\":\"" + name + "\",\"branch\": " + branch + "," + " \"agency\" : \"" + agency + "\"}";
var request = (HttpWebRequest)WebRequest.Create(Url);

                var data = Encoding.UTF8.GetBytes(reqJson);
                request.Method = "POST";
                request.ContentType = "application/json";
                request.ContentLength = data.Length;
                request.KeepAlive = true;
                request.Accept = "application/json";
                request.Headers.Add("Accept-Encoding", "application/gzip");


                Stream dataStream = request.GetRequestStream();
                dataStream.Write(data, 0, data.Length);
                dataStream.Close();

                HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
                var rsp = webResponse.GetResponseStream();
                if (rsp == null)
                {

                }
                using (System.IO.StreamReader rdstrm = new System.IO.StreamReader(webResponse.GetResponseStream()))
                {
                    responseString = rdstrm.ReadToEnd().ToString();
                }

This is the requested JSON 这是请求的JSON

{"AllowAutoRedirect":true,"AllowWriteStreamBuffering":true,"AllowReadStreamBuffering":false,"HaveResponse":false,"KeepAlive":true,"Pipelined":true,"PreAuthenticate":false,"UnsafeAuthenticatedConnectionSharing":false,"SendChunked":false,"AutomaticDecompression":0,"MaximumResponseHeadersLength":64,"ClientCertificates":[],"CookieContainer":null,"SupportsCookieContainer":true,"RequestUri":"http://localhost:9080/api/ucd.php","ContentLength":81,"Timeout":100000,"ReadWriteTimeout":300000,"ContinueTimeout":350,"Address":"http://localhost:9080/api/ucd.php","ContinueDelegate":null,"ServicePoint":{"BindIPEndPointDelegate":null,"ConnectionLeaseTimeout":-1,"Address":"http://localhost:9080/api/ucd.php","MaxIdleTime":100000,"UseNagleAlgorithm":true,"ReceiveBufferSize":-1,"Expect100Continue":true,"IdleSince":"\/Date(1542637743629)\/","ProtocolVersion":{"Major":1,"Minor":1,"Build":-1,"Revision":-1,"MajorRevision":-1,"MinorRevision":-1},"ConnectionName":"http","ConnectionLimit":2147483647,"CurrentConnections":0,"Certificate":null,"ClientCertificate":null,"SupportsPipelining":true},"Host":"localhost","MaximumAutomaticRedirections":50,"Method":"POST","Credentials":null,"UseDefaultCredentials":false,"ConnectionGroupName":null,"Headers":["Content-Type","Accept","Accept-Encoding"],"Proxy":{"Credentials":null},"ProtocolVersion":{"Major":1,"Minor":1,"Build":-1,"Revision":-1,"MajorRevision":-1,"MinorRevision":-1},"ContentType":"application/json","MediaType":null,"TransferEncoding":null,"Connection":null,"Accept":"application/json","Referer":null,"UserAgent":null,"Expect":null,"IfModifiedSince":"\/Date(-62135596800000)\/","Date":"\/Date(-62135596800000)\/","ServerCertificateValidationCallback":null,"CreatorInstance":{},"CachePolicy":{"Level":1},"AuthenticationLevel":1,"ImpersonationLevel":4}

the above is autogenerated while posting JSON request 以上是在发布JSON请求时自动生成的

The receiving PHP code is 接收的 PHP代码是

 <?php

include_once('config.php');
if($_SERVER['REQUEST_METHOD'] == "POST"){


//Posting the data here
$user_id= $_POST['user_id'];
$user_name= $_POST['name'];
$branch= $_POST['branch'];
$agency= $_POST['agency'];



//This below method also tried but the same showing.
/*$portal = isset($_POST['portal']) ? mysqli_real_escape_string($_POST['portal']) : "";
$pax_name = isset($_POST['pax_name']) ? mysqli_real_escape_string($_POST['pax_name']) : "";
$ticket_no = isset($_POST['ticket_no']) ? mysqli_real_escape_string($_POST['ticket_no']) : "";
$adtorch = isset($_POST['adtorch']) ? mysqli_real_escape_string($_POST['adtorch']) : "";
$airline_code = isset($_POST['airline_code']) ? mysqli_real_escape_string($_POST['airline_code']) : "";*/


 // Insert data into data base
 $sql = "INSERT INTO portal_users (pu_user_id, pu_username, pu_branch, pu_agency) VALUES ('" .$user_id."','".$user_name."','".$branch."','".$agency."');";
 $qur = $conn->query($sql);
 if($qur){
 $json = array("status" => 1, "msg" => $user_id);
 }else{
 $json = array("status" => 0, "msg" => "Error adding user!");
 }
}else{
 $json = array("status" => 0, "msg" => "Request method not accepted");
}

mysqli_close($conn);

/* Output header */
 header('Content-type:  application/json');
 echo json_encode($json);
?>

is there any issue at posted value receiving? 帐面价值收取时有什么问题吗? It's a json request. 这是一个json请求。 so I want to use the decode method? 所以我想使用解码方法? I am a beginner, so i don't know to decode. 我是一个初学者,所以我不知道解码。

I have tried this method also 我也尝试过这种方法

$r_val = file_get_contents("php://input");
$r_data = json_decode($r_val, true);


$user_id= $r_data ['user_id'];
$user_name= $r_data ['name'];
$branch= $r_data ['branch'];
$agency= $r_data ['agency'];

you need to receive the json value like this - 您需要像这样接收json值-

$r_val = file_get_contents("php://input");
$r_data = json_decode($r_val, true);

here $r_data is an array. 这里$ r_data是一个数组。 you will get your expected value in this array like below- 您将在此数组中获得期望值,如下所示:

$user_id= $r_data ['user_id'];
$user_name= $r_data ['name'];
$branch= $r_data ['branch'];
$agency= $r_data ['agency'];

TO receive json POST data in php we should use below code 要在php中接收JSON POST数据,我们应该使用以下代码

$postdata = file_get_contents("php://input"); //This will post JSON into $postdata as a JSON string
$postdataArray = json_decode($postdata, true); //This will convert JSON string into array

In your case replace below code 您的情况请替换以下代码

//Posting the data here
$user_id= $_POST['user_id'];
$user_name= $_POST['name'];
$branch= $_POST['branch'];
$agency= $_POST['agency'];

With this code 有了这个代码

$postdata = file_get_contents("php://input"); 
$postdataArray = json_decode($postdata, true);
$user_id= $postdataArray['user_id'];
$user_name= $postdataArray['name'];
$branch= $postdataArray['branch'];
$agency= $postdataArray['agency'];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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