Tuesday, December 9, 2014

HTTP POST and GET using cURL in Linux

Linux provides a nice little command which makes our lives a lot easier.


GET:

with JSON:
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource

with XML:
curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource


POST:
For posting data:
curl --data "param1=value1&param2=value2" http://hostname/resource

For file upload:
curl --form "fileupload=@filename.txt" http://hostname/resource

RESTful HTTP Post:
curl -X POST -d @filename http://hostname/resource

For logging into a site (auth):
curl -d "username=admin&password=admin&submit=Login" --dump-header headers http://localhost/Login
curl -L -b headers http://localhost/
 
 
In cases where the webservice responses are in JSON then it might be
 more useful to see the results in a clean JSON format instead of a very
 long string. Just add | grep }| python -mjson.tool  to the end of curl 
commands here is two examples:

GET approach with JSON result
curl -i -H "Accept: application/json" http://someHostName/someEndpoint | grep }| python -mjson.tool
POST approach with JSON result
curl -X POST -H "Accept: Application/json" -H "Content-Type: application/json" http://someHostName/someEndpoint -d '{"id":"IDVALUE","name":"Mike"}' | grep }| python -mjson.tool

enter image description here
 
 

Example:

curl --header "X-MyHeader: 123" www.google.com
You can see the request that curl sent by adding the -v option.
 
 
Ref: http://stackoverflow.com/questions/14978411/http-post-and-get-using-curl-in-linux