Reputation: 127
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. 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. The data posted from using JSON from asp.net is
JSON POST array from asp.net
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
{"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
The receiving PHP code is
<?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. 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'];
Upvotes: 0
Views: 957
Reputation: 733
TO receive json POST data in php we should use below code
$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'];
Upvotes: 1
Reputation: 59
you need to receive the json value like this -
$r_val = file_get_contents("php://input");
$r_data = json_decode($r_val, true);
here $r_data is an array. 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'];
Upvotes: 1