Tuesday, October 20, 2015

How to request POST and GET using Python ?

I want to share about HTTP request using python, HTTP request can be done using POST or GET method. The main different between POST and GET is on HTTP header, POST method need Content-Type: application/x-www-form-urlencoded definition when sending data.

If you want to know about HTTP header you can refer to wiki page http://en.wikipedia.org/wiki/List_of_HTTP_header_fields or W3 page http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html.

But I will not talk about HTTP Protocol standard in this post, I only will share about how to request POST and GET using python (I use python version 3.4).

POST Method:
# import url Request to create request object
from urllib.request import Request

# import urlopen to send request to web site
from urllib.request import urlopen

# for post request need define Content-Type : application/x-www-form-urlencoded on http header
header = {'Content-Type':'application/x-www-form-urlencoded'}

# create request object
# data query need to encode to byte, it is save to use standart ISO-8859-1
req = Request('http://localhost:8888/p/authenticate/google', 'firstname=amru&lastname=rosyada'.encode('ISO-8859-1'), header)

# send post request
post_response = urlopen(req)

GET Method:
GET code snippet is same with POST but without application/x-www-form-urlencoded on http header data parameter should be None of left it blank.
# import url Request to create request object
from urllib.request import Request

# import urlopen to send request to web site
from urllib.request import urlopen

# create request object
# data query need to encode to byte, it is save to use standart ISO-8859-1
req = Request('http://localhost:8888/p/authenticate/google?firstname=amru&lastname=rosyada', None)

# send post request
get_response = urlopen(req)
Thanks :D

1 comment:

  1. Harrah's Casino New Orleans, New Orleans - Mapyro
    Find your 포천 출장마사지 way around 안성 출장안마 the casino 동해 출장안마 and other gaming action at Harrah's New Orleans 과천 출장마사지 Hotel and Casino. See schedule, reviews and contact 포항 출장샵 info.

    ReplyDelete