Videos
You need to use the cURL library to send this request.
<?php
// Your ID and token
$blogID = '8070105920543249955';
$authToken = 'OAuth 2.0 token here';
// The data to send to the API
$postData = array(
'kind' => 'blogger#post',
'blog' => array('id' => $blogID),
'title' => 'A new post',
'content' => 'With <b>exciting</b> content...'
);
// Setup cURL
$ch = curl_init('https://www.googleapis.com/blogger/v3/blogs/'.$blogID.'/posts/');
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array(
'Authorization: '.$authToken,
'Content-Type: application/json'
),
CURLOPT_POSTFIELDS => json_encode($postData)
));
// Send the request
$response = curl_exec($ch);
// Check for errors
if($response === FALSE){
die(curl_error($ch));
}
// Decode the response
$responseData = json_decode($response, TRUE);
// Close the cURL handler
curl_close($ch);
// Print the date from the response
echo $responseData['published'];
If, for some reason, you can't/don't want to use cURL, you can do this:
<?php
// Your ID and token
$blogID = '8070105920543249955';
$authToken = 'OAuth 2.0 token here';
// The data to send to the API
$postData = array(
'kind' => 'blogger#post',
'blog' => array('id' => $blogID),
'title' => 'A new post',
'content' => 'With <b>exciting</b> content...'
);
// Create the context for the request
$context = stream_context_create(array(
'http' => array(
// http://www.php.net/manual/en/context.http.php
'method' => 'POST',
'header' => "Authorization: {$authToken}\r\n".
"Content-Type: application/json\r\n",
'content' => json_encode($postData)
)
));
// Send the request
$response = file_get_contents('https://www.googleapis.com/blogger/v3/blogs/'.$blogID.'/posts/', FALSE, $context);
// Check for errors
if($response === FALSE){
die('Error');
}
// Decode the response
$responseData = json_decode($response, TRUE);
// Print the date from the response
echo $responseData['published'];
I think cURL would be a good solution. This is not tested, but you can try something like this:
$body = '{
"kind": "blogger#post",
"blog": {
"id": "8070105920543249955"
},
"title": "A new post",
"content": "With <b>exciting</b> content..."
}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.googleapis.com/blogger/v3/blogs/8070105920543249955/posts/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json","Authorization: OAuth 2.0 token here"));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
$result = curl_exec($ch);
Starting with Requests version 2.4.2, you can use the json= parameter (which takes a dictionary) instead of data= (which takes a string) in the call:
Copy>>> import requests
>>> r = requests.post('http://httpbin.org/post', json={"key": "value"})
>>> r.status_code
200
>>> r.json()
{'args': {},
'data': '{"key": "value"}',
'files': {},
'form': {},
'headers': {'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'close',
'Content-Length': '16',
'Content-Type': 'application/json',
'Host': 'httpbin.org',
'User-Agent': 'python-requests/2.4.3 CPython/3.4.0',
'X-Request-Id': 'xx-xx-xx'},
'json': {'key': 'value'},
'origin': 'x.x.x.x',
'url': 'http://httpbin.org/post'}
It turns out I was missing the header information. The following works:
Copyimport requests
url = "http://localhost:8080"
data = {'sender': 'Alice', 'receiver': 'Bob', 'message': 'We did it!'}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post(url, data=json.dumps(data), headers=headers)
You don't need to build up your JSON using JObject. You can either use anonymous classes or paste your JSON sample using Paste JSON as Classes. Based on your JSON sample an anonymous object would look like this.
var body = new
{
accountrefrence = "XXXXX",
messages = new[]
{
new
{
to = "XXXX",
body = "XXX!"
}
}
}
And actual classes might look like this:
public class Rootobject
{
public string accountreference { get; set; }
public Message[] messages { get; set; }
}
public class Message
{
public string to { get; set; }
public string body { get; set; }
}
The easiest way to manage JSON serialization is to use objects instead of raw strings or trying to manually compose the output (as it looks like you're doing here).
As you're already using Newtonsoft libraries for it, it will be quite easy to do.
Frist thing would be to create an object that represents the data you want to send to the api. As stated in another answer here, you can simply do this by copying your sample JSON and in VS do a "Paste JSON as classes".
Most likely, the resulting classes will be something like:
public class Rootobject
{
public string accountreference { get; set; }
public Message[] messages { get; set; }
}
public class Message
{
public string to { get; set; }
public string body { get; set; }
}
What you can do now is a method that grabs your data and populates the properties of this objects. As you're not providing much details on what are you doing I will simply assume that it is possible for you to have a method that receives the string values somehow.
public void ComposeAndSendJson(string accountReference, string toAddress, string messageBody)
{
RootObject whatIwanttoSend = new RootObject();
Message messageComposed = new Message();
messageComposed.to = toAddress;
messageComposed.body = messageBody;
whatIwanttoSend.accountReference = accountReference;
//I'm doing a pretty bad aproach but it's just to ilustrate the concept
whatIwanttoSend.messages.toList().Add(messageComposed);
var jsonData = JsonConvert.SerializeObject(whatIwanttoSend);
//As you're working on async, you may need to do some working on here. In this sample i'm just calling it in Sync.
var ApiResponse = PostAsync("YOURENDPOINT",jsonData).Result();
//Do something else with the response ...
}
protected async Task<Task<HttpResponseMessage> PostAsync(Uri endpoint, object payload)
{
using (var httpClient = NewHttpClient())
{
//You have to tell the API you're sending JSON data
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Execute your call
var result = await httpClient.PostAsJsonAsync(endpoint, payload);
//Basic control to check all went good.
if (result.IsSuccessStatusCode)
{
return result;
}
//Do some management in case of unexpected response status here...
return result; //Statuscode is 400 here.
}
}
I hope this sets you in the right path.