Post Request with JSON Body

POST request with JSON body

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'];

How to POST JSON data with Python Requests?

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:

>>> 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'}

How do I send a JSON string in a POST request in Go

I'm not familiar with napping, but using Golang's net/http package works fine (playground):

func main() {
url := "http://restapi3.apiary.io/notes"
fmt.Println("URL:>", url)

var jsonStr = []byte(`{"title":"Buy cheese and bread for breakfast."}`)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
req.Header.Set("X-Custom-Header", "myvalue")
req.Header.Set("Content-Type", "application/json")

client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()

fmt.Println("response Status:", resp.Status)
fmt.Println("response Headers:", resp.Header)
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response Body:", string(body))
}

Sending a POST request with JSON body using Guzzlehttp

The startpoint of the payload data should be an array in order to encode it to json. Otherwise you might encounter problems since you are then trying to encode data already in json format.

Step-1) Create a variable $payload where you store the data you wish to send with your request.

Step-2) Add body into your request (below headers), where $payload is your data, and json-encode the $payload.

'body'    => json_encode($payload)

To simplify the test you can also just add the pure text string.

'body' => json_encode('mydata goes here...')

How to perform a post request using json file as body

I recommend you to parse JSON file to String from this topic:
How to read json file into java with simple JSON library

Then you can take your JSON-String and parse to Map (or whatever you specify) by popular and simple library Gson.

String myJSON = parseFileToString();  //get your parsed json as string
Type mapType = new TypeToken<Map<String, String>>(){}.getType(); //specify type of
your JSON format
Map<String, String> = new Gson().fromJson(myJSON, mapType); //convert it to map

Then you can pass this map as a request body to your post. Dont pass any JSON data as URL in POST methods.
Data in URL isn't good idea as long as you are not using GET (for example).

You can also send whole JSON (in String version) as parameter, without converting it to Maps or objects. This is only example :)

And if you want to pass this map in your POST method you can follow this topic:
Send data in Request body using HttpURLConnection

[UPDATE] it worked fine, result 200 OK from server, no exceptions, no errors:

   package com.company;

import java.io.DataInputStream;
import java.io.File;
//import org.json.JSONObject;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class TestAuth {

public static void main(String[] args) {
// TODO Auto-generated method stub

File file = new File("test.json");
try {
JSONParser parser = new JSONParser();
//Use JSONObject for simple JSON and JSONArray for array of JSON.
JSONObject data = (JSONObject) parser.parse(
new FileReader(file.getAbsolutePath()));//path to the JSON file.
System.out.println(data.toJSONString());

String paramValue = "param\\with\\backslash";
String yourURLStr = "http://host.com?param=" + java.net.URLEncoder.encode(paramValue, "UTF-8");

URL url2 = new URL("https://0c193bc3-8439-46a2-a64b-4ce39f60b382.mock.pstmn.io");
HttpsURLConnection conn = (HttpsURLConnection) url2.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Authorization", "Bearer aanjd-usnss092-mnshss-928nss");

conn.setDoOutput(true);
OutputStream outStream = conn.getOutputStream();
OutputStreamWriter outStreamWriter = new OutputStreamWriter(outStream, "UTF-8");
outStreamWriter.write(data.toJSONString());
outStreamWriter.flush();
outStreamWriter.close();
outStream.close();
String response = null;

System.out.println(conn.getResponseCode());
System.out.println(conn.getResponseMessage());

DataInputStream input = null;
input = new DataInputStream (conn.getInputStream());
while (null != ((response = input.readLine()))) {
System.out.println(response);
input.close ();
}
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
}

Let me know if that answer fixed your problem. Greetings!

Fetch: POST JSON data

With ES2017 async/await support, this is how to POST a JSON payload:

(async () => {  const rawResponse = await fetch('https://httpbin.org/post', {    method: 'POST',    headers: {      'Accept': 'application/json',      'Content-Type': 'application/json'    },    body: JSON.stringify({a: 1, b: 'Textual content'})  });  const content = await rawResponse.json();
console.log(content);})();

How do I POST JSON data with cURL?

You need to set your content-type to application/json. But -d (or --data) sends the Content-Type application/x-www-form-urlencoded, which is not accepted on Spring's side.

Looking at the curl man page, I think you can use -H (or --header):

-H "Content-Type: application/json"

Full example:

curl --header "Content-Type: application/json" \
--request POST \
--data '{"username":"xyz","password":"xyz"}' \
http://localhost:3000/api/login

(-H is short for --header, -d for --data)

Note that -request POST is optional if you use -d, as the -d flag implies a POST request.


On Windows, things are slightly different. See the comment thread.



Related Topics



Leave a reply



Submit