I have already asked this question but need further help.
c# is not sending json request to PHP
I am trying to send data from c# to PHP webpage using the JSON & REST API HTTP request.
On PHP page I see "String (0)"
c# Code
user user = new user();
{
user.firstname = "aaaa";
user.secondname = "aaaaaaaaaaa";
user.email = "aaa";
user.phonenumber = "aaa";
};
string json = JsonConvert.SerializeObject(user);
HttpWebRequest request = WebRequest.Create("https://scs.agsigns.co.uk/test.php") as HttpWebRequest;
request.ContentType = "application/json";
//request.Accept = "application/json, text/javascript, */*";
request.Method = "POST";
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(json);
}
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream stream = response.GetResponseStream();
string json1 = "";
using (StreamReader reader = new StreamReader(stream))
{
while (!reader.EndOfStream)
{
json1 += reader.ReadLine();
}
}
DisplayAlert("Alert", json1, "OK");
PHP
$content = file_get_contents("php://input");
var_dump($content);
In c# I get this alert
c# display alert message
In the PHP webpage, I see following
PHP page shows string(0)
What I want to get data which app sendand save into MySql.
EDIT
I have ammended the PHP file code to save data in MySQL.
I am getting error
Notice: Trying to get property 'name' of non-object in C:\inetpub\scs\test.php on line 16
This is my PHP code.
//Receive the RAW post data.
$content = file_get_contents("php://input");
$obj = json_encode($content);
$insert_stmt = $mysqli->prepare("INSERT INTO test (name,address) VALUES (?,?)");
$name =$obj->{'name'};
$address = $obj->{'address'};
$insert_stmt->bind_param("ss", $name, $address);
//Execute the statement
$insert_stmt->execute();
You should use HttpClient instead of HttpWebRequest
Your request would look like this with HttpClient
public async void SendUserDataToServer()
{
user user = new user();
{
user.firstname = "aaaa";
user.secondname = "aaaaaaaaaaa";
user.email = "aaa";
user.phonenumber = "aaa";
};
string json = JsonConvert.SerializeObject(user);
using (var client = new HttpClient())
{
var response = await client.PostAsync(
"https://scs.agsigns.co.uk/test.php",
new StringContent(json, Encoding.UTF8, "application/json"));
}
DisplayAlert("Alert", json, "OK");
}
Reference: this
Related
Here is my code below. Getting the token from shopify works fine. However while creating a new product it keeps giving me an error. I've tried everything possible and it still does not work. Any advice would be appreciated.
Here's how I call the CreateNewProduct method passing the access token from shopify and the shopname with the products endpoint.
CreateNewProduct(accessTokenDTO.access_token, "https://{myshopname}.myshopify.com/admin/api/2020-10/products.json");
Here's the method below.
public static void CreateNewProduct(string token, string Url)
{
Uri shopUri = new Uri(Url);
HttpWebRequest GETRequest = (HttpWebRequest)WebRequest.Create(shopUri);
GETRequest.ContentType = "application/json";
GETRequest.Headers.Add("X-Shopify-Access-Token", token);
GETRequest.PreAuthenticate = true;
GETRequest.Method = "PUT";
using (var streamWriter = new StreamWriter(GETRequest.GetRequestStream()))
{
string json = "{\"product\": { \"title\": \"Burton Custom Freestyle 151\", \"body_html\": \"<strong>Good snowboard!</strong>\", \"vendor\": \"Burton\", \"product_type\": \"Snowboard\", \"tags\": [ \"Barnes & Noble\", \"John's Fav\", \"\\Big Air\\]}";
streamWriter.Write(json);
streamWriter.Flush();
}
HttpWebResponse GETResponse = (HttpWebResponse)GETRequest.GetResponse();
var encoding = ASCIIEncoding.ASCII;
using (var reader = new System.IO.StreamReader(GETResponse.GetResponseStream(), encoding))
{
string responseText = reader.ReadToEnd();
Debug.WriteLine("Response Text: " + responseText);
}
GETResponse.Close();
}
400 BadRequest normally refers to the body you are sending with your request is not valid according to the api.
Wheni look at your string that is supposed to be a json, it shows invalid data at the end.
[ \"Barnes & Noble\", \"John's Fav\", \"\\Big Air\\]}";
You are missing closing quotes after Big Air. Also, not sure if those backslash are supposed to be there around Big Air but definitely the missing closing quotes would seem to be the issue
There was an issue with the json not being formatted correctly and method was a PUT instead of POST. See working code below.
public static void CreateNewProduct(string token, string Url)
{
Uri shopUri = new Uri(Url);
HttpWebRequest GETRequest = (HttpWebRequest)WebRequest.Create(shopUri);
GETRequest.ContentType = "application/json";
GETRequest.Headers.Add("X-Shopify-Access-Token", token);
GETRequest.PreAuthenticate = true;
GETRequest.Method = "POST";
using (var streamWriter = new StreamWriter(GETRequest.GetRequestStream()))
{
string json = "{\"product\": { \"title\": \"Burton Custom Freestyle 151\", \"body_html\": \"<strong>Good snowboard!</strong>\", \"vendor\": \"Burton\", \"product_type\": \"Snowboard\"} }";
streamWriter.Write(json);
streamWriter.Flush();
}
HttpWebResponse GETResponse = (HttpWebResponse)GETRequest.GetResponse();
var encoding = ASCIIEncoding.ASCII;
using (var reader = new System.IO.StreamReader(GETResponse.GetResponseStream(), encoding))
{
string responseText = reader.ReadToEnd();
Debug.WriteLine("Response Text: " + responseText);
}
GETResponse.Close();
}
I am trying to send push notification on android device with FCM in C#.Net, but I am getting "InvalidRegistration" error message.
I have used the same from Postman and R-Client as well, but still getting same error.
public String SendNotificationFromFirebaseCloud()
{
string DeviceToken = "RegToken";
string YOUR_FIREBASE_SERVER_KEY = "ServerKey";
var result = "-1";
var webAddr = "https://fcm.googleapis.com/fcm/send";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add("Authorization:key=" + YOUR_FIREBASE_SERVER_KEY);
httpWebRequest.Headers.Add(string.Format("Sender: id={0}", "MySenderId"));
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"to\":\"" + DeviceToken + "\",\"data\":{\"message\": \"Welcome\"}}";
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
{"multicast_id":8671409506357877791,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
"invalid registration" indicates that the device token is incorrect, does not point to an existing device.
Mind that this does not mean a device that's turned off, it means that no device (currently) uses that token at all.
In other words it's an indication of a bad recipient address, effectively the equivalent of an HTTP 404 error.
I am trying to verify username, password, and software token number of a C# Windows Form to values in MySQL database.
My C# Code:
private void btnlogin_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(txtusername.Text))
{
MessageBox.Show("Please insert username");
}
if (String.IsNullOrEmpty(txtpassword.Text))
{
MessageBox.Show("Please insert password");
}
var username = txtusername.Text;
var password = txtpassword.Text;
string Token = "28956";
var SoftwareToken = token;
WebRequest request = WebRequest.Create("https://mydomain.com.au/Verification.php?username=username&password=password&Token=SoftwareToken");
request.Method = "GET";
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
var responseFromServer = reader.ReadToEnd();
responseFromServer.ToArray();
/*I have tried:
responseFromServer.ToArray();(because result on php page is an array.
I have tried responseFromServer.ToString();*/
MessageBox.Show(responseFromServer);
}
My PHP code (Web service):
<?php
// Database Structure
require_once('connect.php');
//Get password from the database for the user
$stmtus = $conn->prepare("SELECT password from `Users` where `email` = :Username");
$stmtus->bindParam(':Username', $username);
$username= $_GET['username'];;
$stmtus -> execute();
$password = $stmtus->fetch();
$un = $_GET['username'];
$pw = $_GET['password'];
$ust = $_GET['Token'];
if(password_verify($pw, $password[0])){
$stmt = $conn->prepare("SELECT
COUNT(Token) AS cnt FROM `SoftwareToken`
LEFT JOIN User ON iduser = SoftwareToken.Consultant
WHERE Token = '$ust'
AND username = '$un'");
$stmt->bindValue(':Username', $un);
$stmt->bindValue(':Token', $ust);
$stmt->execute();
$result= array();
while($SToken= $stmt->fetch(PDO::FETCH_OBJ)){
array_push($result, $SToken->cnt);
}
echo json_encode($result);
}
$conn = null;
?>
I am battling to understand how I call the web service from the C# application, how do I pass the variables from the C# application to the web service and how do I return the json_encode to the C# application from the web service.
I am not a full-time programmer and this is my first encounter with web services. If there are any suggestions on how to improve either of the codes, I would much appreciate.
UPDATE
I have updated my code as assisted. When I run the php code with variables it runs and gives me a $result (array). A numeral answer 1.
When I test my code to display the result in a MessageBox, the MessageBox is empty. Why ?
Of course you can call WebService from C#.
There is a built in calss in System.
One Way:
WebRequest request = WebRequest.Create("http://localhost:8080/?username=john");
request.Method="GET";
WebResponse response = request.GetResponse();
Other Way:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:8080/");
HttpResponseMessage response = await client.PostAsJsonAsync( "api/user", userName);
response.EnsureSuccessStatusCode();
Code which I used:
var username = txtusername.Text;
var password = txtpassword.Text;
string Token = "28956";
var url = "https://mydomain.com.au/LoginVerification.php?";
var var = "username=" + username + "&password=" + password + "&Token=" + Token ;
var URL = url + var;
//MessageBox.Show(URL);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
var responseFromServer = reader.ReadToEnd();
//MessageBox.Show(responseFromServer);
// Display the content.
if (responseFromServer == "\n Allow")
{
MessageBox.Show("Success");
}
I'm new in c# ,and want to send json post to server with this code:
var httpWebReques = (HttpWebRequest) WebRequest.Create(#"http://myDomain/api/FileCommand/AddGig ");
httpWebReques.ContentType = "application/json";
httpWebReques.Method = "POST";
using (var streamWriter=new StreamWriter(httpWebReques.GetRequestStream()))
{
JObject obj = JObject.FromObject(new
{
PhoneNumber= phoneNumber,
TrafficGigCount="1",
PaymentAmountRial="2000",
PaymentTrackingNo="123434"
});
string json = obj.ToString(); //"{\"PhoneNumber\":\""+phoneNumber+"\"," + "\"TrafficGigCount\":\"1\","+ "\"PaymentAmountRial\":\"1000\","+ "\"PaymentTrackingNo\":\"1254\"}";
streamWriter.Write(obj);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse) httpWebReques.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
every thing is ok and now want to send server cookie with this code:
httpWebReques.CookieContainer = new CookieContainer();
httpWebReques.CookieContainer.SetCookies(new Uri("http://www.tclnet.ir/"), cookies);
for that purpose write this code:<br/>
var httpWebReques = (HttpWebRequest) WebRequest.Create(#"http://www.tclnet.ir/api/FileCommand/AddGig ");
httpWebReques.ContentType = "application/json";
httpWebReques.Method = "POST";
httpWebReques.CookieContainer = new CookieContainer();
httpWebReques.CookieContainer.SetCookies(new Uri("http://www.tclnet.ir/"), cookies);
using (var streamWriter=new StreamWriter(httpWebReques.GetRequestStream()))
...
but when receive to this line:
var httpResponse = (HttpWebResponse) httpWebReques.GetResponse();
get this error:
The remote server returned an error: (500) Internal Server Error.
How can i solve that?thanks.
my error:
Firstly, I understand this code isn't necessarily "safe" and is VERY basic. I'm learning how to consume rest services with web forms in C# (both are new topics for me). Pretty much the only thing there is 2 textboxes for authentication credentials, a query textbox and button to send the request with a label. I just want to enter the ID1 into the textbox, and then return the First and Last name for the entry with that ID.
I have tried many different ways after thoroughly searching the web but can't seem to figure out the issue.
The Issue: The StreamReader data from the WebResponse isn't coming back as XML.
The Question: How do I return the XML tags that I want? Do I need to parse them? If so, how?
The XDoc version is returning nothing while the straight stream reader is returning a string with some data in addition to numbers that shouldn't be there and no angle brackets. Below is the code as it stands now:
if (QueryTextBox2.Text != "")
{
string tableName = "Entry";
string requestURL = "https://myUrl.com/rest/services/" + tableName;
HttpWebRequest request = WebRequest.Create(requestURL) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "text/xml; encoding:='charset=utf-8'";
request.Headers["CustomUserName"] = TextBox1.Text;
request.Headers["CustomPassword"] = TextBox3.Text;
string xml = "<Entry><ID1>" + QueryTextBox2.Text + "</ID1></Entry>";
byte[] byteArray = Encoding.UTF8.GetBytes(xml.ToString());
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.OK) {
Stream postData = response.GetResponseStream();
StreamReader reader = new StreamReader(postData, Encoding.UTF8);
string result = reader.ReadToEnd();
Label2.Text = result;
} else
{
Label2.Text = "There was an error: " + response.StatusDescription;
}
}
else
{
TextBox2.Text = "Please Enter an ID";
}
}
}
I have also tried using:
XDocument doc = new XDocument();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
doc = XDocument.Parse(reader.ReadToEnd());
string fname = doc.Root.Element("NameFirst").Value;
string lname = doc.Root.Element("NameLast").Value;
Label2.Text = fname + lname;
to replace the whole block within: if statusCode == OK.
The data returned from the firefox Poster add-on is:
<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom">
<title type="text">Search Results</title>
<id>https://myUrl.com/rest/services</id>
<updated>2015-10-07T09:51:32Z</updated>
<link rel="self" type="application/atom+xml" href="https://myUrl.com/rest/services" />
<entry>
<id>https://myUrl.com/rest/services</id>
<Entry>
<ID1>900009</ID1>
<NameLast>Smith</NameLast>
<NameFirst>Tom</NameFirst>
<NameTitle></NameTitle>
<NamePreferred>Alex</NamePreferred>
<NameWeb>tsmith</NameWeb>
<NameOther></NameOther>
<NameInitials></NameInitials>
</Entry></content></entry></feed>
I've removed a lot of the response data because it's so large and anonymized it all for the most part so keep that in mind.
I would use System.Net.Http.HttpClient, it has a much easier interface for consuming http requests.
I haven't tested the document parsing, but just follow the nested levels in until you find the element you want.
async void Main()
{
var textBox2String = "2"
if (!string.IsNullOrEmpty(textBox2String))
{
const string table = "Entry";
var client = new HttpClient();
var url = $"https://myurl.com/rest/services/{table}";
var xml = $"<Entry><ID1>{textBox2String}</ID1></Entry>";
client.DefaultRequestHeaders.TryAddWithoutValidation("CustomUserName", "username");
client.DefaultRequestHeaders.TryAddWithoutValidation("CustomPassword", "password");
var response = await client.PostAsync(url, new StringContent(xml, Encoding.UTF8, "text/xml"));
var content = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var document = XDocument.Parse(content);
var entry = document.Root.Element(table);
var firstName = entry.Element("FirstName").Value;
var lastName = entry.Element("LastName").Value;
$"{firstName} {lastName}".Dump();
}
else
{
Console.WriteLine($"An error occurred processing this request: {content}");
}
}
else
{
textBox2String = "Please enter an ID";
}
}