Wednesday, 13 August 2014

Using HTTP POST and GET using cURL

Background

cURL is a command line utility to perform GET and POST requests. It comes really handy for testing REST APIs. For debian based Linux systems you can simply install it

  • sudo apt-get install curl

But you can install  it in windows as well. You can use it from cygwin as well (select the appropriate package while installing). For installing cURL in windows I had written a post some time back. You can refer the same -


That's about installation. In this post we will see the usage if cURL command.



Using cURL command

As we know there are two majorly used REST APIs - GET and POST. Lets see how to perform these actions using cURL - 

GET

  1. With json :

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

  2. With XML :

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

POST


  1. For posting data :

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

  2. For File Upload :

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

  3. RESTful HTTP post :

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

  4. 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/

POST with some JSON data

You can use -H to set the header while using cURL command 

Example  - 
  • -H "Content-Type: application/json"
So your complete command would look something like -

curl -H "Content-Type: application/json" -d '{"username":"xyz","password":"xyz"}' http://localhost:3000/api/login

Difference between GET and POST


Related Links


No comments:

Post a Comment

t> UA-39527780-1 back to top