-
Notifications
You must be signed in to change notification settings - Fork 40
/
HttpService.py
64 lines (54 loc) · 1.86 KB
/
HttpService.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#python2.5~2.7
import optparse
import socket
import urllib
import urllib2
import httplib2
class HttpService:
def StringBody(self, url, protocol, body, header):
try:
h = httplib2.Http()
response, content = h.request(url, protocol, body, headers=header)
if response.status==200:
return content, True
return content, False
except Exception,ex:
print str(ex)
return str(ex),False
def post(self, url, params, timeout=50):
return self.__service(url, params,timeout=timeout)
def get(self,url,timeout=50):
return self.__service(url, timeout=timeout)
#timeout 50s
def __service(self, url, params=None, timeout=50):
old_timeout = socket.getdefaulttimeout()
socket.setdefaulttimeout( timeout )
try:
request = urllib2.Request( url, urllib.urlencode(params) )
request.add_header( 'Accept-Language', 'zh-cn' )
response = urllib2.urlopen( request )
content = response.read()
if response.code==200:
return content, True
return content, False
except Exception,ex:
return str(ex),False
finally:
if 'response' in dir():
response.close()
socket.setdefaulttimeout( old_timeout )
if __name__ == '__main__':
get_data = ''
get_data += 'id=123'
print get_data
#StringBody is your content
post_data = '{"username":"xxx","password":"xxx","modules":[{"path":"heh","version":"1.0.0.0"}]}'
print post_data
http_service = HttpService()
try:
content, status = http_service.StringBody("http://www.xxx.com?"+get_data, 'POST', post_data, {'content-type':'text/plain'})
print content
except Exception,ex:
print str(ex)
print 'time out'
pass