Send form values into JSON and php api using QT - php

I have written an API that I want to accept form values for the HTTP header POST.
Using PHP, I can make use of the API link using the following code:
$data = array(
"authorid" => $_POST['author'],
"filmid" => $_POST['film'],
"content" => "".$_POST['content']."",
"score" => $_POST['score']
);
$post = json_encode($data);
$ch = curl_init('http://www.website.co.uk//v1/review/');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array(
'Content-Type: application/json',
'Content-Length: ' . strlen($post))
);
$result = curl_exec($ch);
echo $result;
I am however using the API in a QT application.
What is the best way to store the form values and when they are submitted, send the HTTP header request POST along with the array of data to the link I gave above.
Got no idea how to achieve this!
Thanks,
Luke.

There are tons of questions like this here, just browse through them and find what is closest to your situation. This shows how to do a POST request. Here is another one with JSON serializiation, just google "qt post qnetworkrequest json" and there should be tons of answers.

Related

Modifying php script to have POST request in cURL for a JSON upload

I have an existing PHP script, which essentially connects to 2 databases each on a different server and performs a few MySQL queries on each. The ultimate results are stored in a data array which is used to write said results into a JSON file.
All of this works perfectly. The data is inserted into the mysql table correctly and the JSON file is exactly the way it should be.
However, I need to add a block to the end of my script that makes a POST request to one of our affiliate's API and upload the info there. We're currently manually uploading this JSON file to the api instance but we have the configuration data for their server to use in a POST request now so that when this script is run it automatically sends the data rather than us having to manually update it.
The main thing is I'm not exactly sure how to go about that. I've started with code for doing this but I'm not familiar with cURL so I don't know the best way to structure this in php.
Here is an example the affiliate gave me in cURL command line syntax:
curl \
-H "Authorization: Token AUTH_TOKEN" \
-H "Content-Type: CONTENT_TYPE" \
-X POST \
-d '[{"email": "jason#yourcompany.com", "date": "8/16/2016", "calls": "3"}]'
\
https://endpoint/api/v1/data/DATA_TYPE/
I have my auth token, my endpoint URL and my content type is JSON, which can be seen in my code below. Also, I have an array instead of the example for the body above.
and here's the affected part of my code:
//new array specifically for the final JSON file
$content2 = [];
//creating array for new fetch since it now has the updated extension IDs
while ($d2 = mysqli_fetch_array($data2, MYSQLI_ASSOC)) {
// Store the current row
$content2[] = $d2;
}
// Store it all into our final JSON file
file_put_contents('ambitionLog.json', json_encode($content2, JSON_PRETTY_PRINT ));
//Beginning code to upload to Ambition API via POST
$url = 'endpoint here';
//Initiate CURL
$ch = curl_init($url);
//JSON data
$jsonDataEncodeUpload = json_encode($content2, JSON_PRETTY_PRINT);
//POST via CURL
curl_setopt($ch, CURLOPT_POST, 1);
//attach JSON to post fields
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncodeUpload);
//set content type
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//execuate request
$postResult = curl_exec($ch);
So, like I said, nothing about the file or the data needs to be changed, I just need to have this cURL section take the existing array that's being written to a JSON file and upload it to the API via post. I just need help making my php syntax for curl match the command line example.
Thanks for any possible help.
Have you tried with file_get_contents ( http://en.php.net/file_get_contents ).
$postdata = http_build_query(
array(
'var1' => 'some content',
'var2' => 'doh'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://example.com/submit.php', false, $context);
I have found the answer on stackoverflow How to post data in PHP using file_get_contents?
Here is worked example of code. Check $err may be it will be helpful.
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $_POST('data'));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
$result = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err = curl_error($ch);
curl_close($ch);

Convert URL encoded to JSON object

I've never worked with JSON objects before but I think this is probably the best route for what I'm trying to achieve (if you think there is a better option please let me know, though I cannot use SOAP)
I am trying to submit some data via POST to an API in order to add some data to a newsletter list which is stored as XML. Here is the documentation for the request I am trying to complete: https://api.dotmailer.com/v2/help/wadl#PostAddressBookContacts
When visiting the API url and authenticating I see data laid out in the following:
<ArrayOfApiContact xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://apiconnector.com">
<ApiContact>
<Id>1058905201</Id>
<Email>email#email.co.uk</Email>
<OptInType>Unknown</OptInType>
<EmailType>Html</EmailType>
<DataFields i:nil="true"/>
<Status>Subscribed</Status>
</ApiContact>
</ArrayOfApiContact>
So I have attempted to replicate as such, using a variable instead of a hardcoded email:
$xml = array(
'id' => urlencode('123456789'),
'email' => urlencode($useremail),
'optInType' => urlencode('Unknown'),
'emailType' => urlencode('Html'),
'dataFields' => urlencode(':null'),
'status' => urlencode('Subscribed')
);
I am combining the array here:
foreach($xml as $key=>$value) { $xml_string .= $key.'='.$value.'&'; }
And then using cURL to POST the request to the API, with my authentication (apipassword and apiemail which the username)
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$auth_url);
curl_setopt($ch,CURLOPT_POST, count($xml));
curl_setopt($ch,CURLOPT_POSTFIELDS, $xml_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, "$apiemail:$apipassword");
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); //get status code
$result = curl_exec ($ch);
curl_close ($ch);
I have already tested this without the POST and I do indeed get the data back in this form:
[{"id":1058905201,"email":"email#email.co.uk","optInType":"Unknown","emailType":"Html","dataFields":null,"status":"Subscribed"}]
So I know the auth is working and the data is coming back correctly, but now when I try to POST my data I get:
{"message":"Content type \"application/x-www-form-urlencoded\" is not supported. Please use one of: application/json,application/xml ERROR_CONTENT_TYPE_IS_NOT_SUPPORTED"}
So how do I convert my array which is URL encoded into something readable by the API?
Try a content type of application/json like so:
curl_setopt($ch, CURLOPT_HTTPHEADER, array('content-type: application/json'));
Two things here (a) content-type header JSON missing and (b) payload not JSON.
// setup request to send json via POST.
$payload = json_encode(array("json"=> $data)); // or json_encode(array($data));
curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );
// set proper content-type for sending JSON
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));

How to send and receive data to/from an API using CURL?

I have to make an API. For this, I will receive the data from the mobile devices as JSON using POST. I have to work with this data and send the response back to the devices also as JSON.
But I don't know how to take the data that I will receive. I have tried to make some tests using CURL to see how can I take this data but the $_POST is always empty. Can you please tell me how to send the data as JSON format to the API using CURL and how can I receive this data so I can work with it and send it back as response?
These are my test files:
curl.php:
//set POST variables
$url = 'http://test.dev/test.php';
$data = array(
'fname' => 'Test',
'lname' => 'TestL',
'test' => array(
'first' => 'TestFirst',
'second' => 'TestSecond'
)
);
//open connection
$ch = curl_init($url);
$json_data = json_encode($data);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json_data))
);
// execute post
$result = curl_exec($ch);
echo $result;
//close connection
curl_close($ch);
test.php:
var_dump($_POST);
The response that I get is:
array(0) { }
You need to pass the POST data as a URL query string or as an array, the problem is you post data in JSON format, but PHP does not parse JSON automatically, so the $_POST array is empty. If you want it, you need do the parsing yourself in the test.php:
$raw_post = file_get_contents("php://input");
$data = json_decode($raw_post, true);
print_r($data);
same questions: 1 2

How to send and receive JSON data between two servers via php

Obviously I am not using the right keywords in my searches or am not understanding what others have written in blogs or forums, et al.
Looking for information on passing data between two servers. The data will be preferably contained within a JSON array.
If you know of someone who has written a blog fully encompassing this I would really like a chance to read it. Otherwise could you offer some thoughts?
More detailed:
As a user visits a page a PHP function will be called and some data will be "packaged up" in a JSON array and then a POST command to the other server. The second server after receiving the POST will do some processing and then "package up" some data and return it in a JSON array. Then the user will be presented with the results.
With the following I am receiving a HTTP 200 response. Just no data.
SITE 1:
$data_string = json_encode(array('user_id'=>123));
$ch = curl_init('http://site2.dev/retrieve');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string)
));
$result = curl_exec($ch);
$status = curl_getinfo($ch);
curl_close($ch);
$result = json_decode($result);
SITE 2:
public function retrieve() {
return json_encode(array('some'=>'456'));
}
The Json array was chosen as it can be encrypted and yes HTTPS will be used in the final environment.
Both servers will have Laravel 4 as the PHP Framework.
Thank you for your thoughts and comments.
Add this:
curl_setopt($ch, CURLOPT_HEADER, 0);
and put quotes on content-length:
curl_setopt($ch, CURLOPT_HTTPHEADER,
array('Content-Type: application/json','"Content-Length: ' . strlen($data_string) . '"'));

How to make a JSON Curl request to an api url, getting null

This should be simple I think but I just can't fathom it.
I need to make a request to a url in the following format:
http://ratings.api.co.uk/business/{lang}/{fhrsid}/{format} where lang will be set to en-GB the fhrsid is an identifier and format is json.
I tried the following but I am just getting null in return:
$data = array("lang" => "en-GB", "fhrsid" => "80928");
$data_string = json_encode($data);
$ch = curl_init('http://ratings.api.co.uk/business/json');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string)) );
$Jsonresult = curl_exec($ch);
curl_close($ch);
var_dump(json_decode($Jsonresult));
Any help gratefully received
You are currently posting the data to the URL, while you say you want to put the data in the URL itself.
I.e. now you submit {"lang:"en-GB","fhrsid":80928} to the URL http://ratings.api.co.uk/business/json, but instead you want to retrieve the URL http://ratings.api.co.uk/business/en-GB/80928/json.
Don't use POST as request type, don't specify postfields, don't specify content-length, and do put the data in your URL.
Sending data as arguments is different than sending it within the URL.
If you require a url format of http://ratings.api.co.uk/{lang}/{fhrsid}/{format}, then you must make your curl_init string match that format.

Categories