Skip to content

Instantly share code, notes, and snippets.

@ykame
Created September 20, 2015 17:46
Show Gist options
  • Save ykame/3ad07eaf7c769d99700c to your computer and use it in GitHub Desktop.
Save ykame/3ad07eaf7c769d99700c to your computer and use it in GitHub Desktop.
#!/usr/bin/python
import urllib, urllib2
import sys
#import json # if you use json.
def requestURL(url, method="GET", params={}, headers={}, proxy=""):
## IF YOU USE PROXY.
if proxy:
proxy_support = urllib2.ProxyHandler({})
opener = urllib2.build_opener(proxy_support)
urllib2.install_opener(opener)
# add parameters
#data = json.dumps(params) # J S O N
data = urllib.urlencode(params) # P A R M
if method == 'GET':
req = urllib2.Request(url + ('?%s' % data)) # G E T
else:
req = urllib2.Request(url, data) # P O S T
# add headers
if headers:
for h in headers:
req.add_header(h, headers[h])
res = urllib2.urlopen(req).read()
#res = res.decode('utf-8')
return res
url = 'https://example.com/'
method = 'GET'
params = {
#'q': 'test',
#'xxx': 'xxx'
}
headers = {
#'Content-Type': 'application/json',
#'Cookie': 'lang=ja'
}
requestURL(url, method, params, headers)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment