python2 http请求post、get
發送post,json
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import urllib2
data = {"userAccount":"zhaoyun", "userPwd":"0e7517141fb53f21ee439b355b5a1d0a", "loginKey": ""}
headers = {'Content-Type': 'application/json'}
url='http://192.168.7.160/ipc_moudle/sysUser/login/'
req = urllib2.Request(url=url, data=json.dumps(data), headers=headers)
res = urllib2.urlopen(req)
res = res.read()
print(res)
?
發送get
import urllib,urllib2 url='http://192.168.199.1:8000/mainsugar/loginGET/' textmod ={'user':'admin','password':'admin'} textmod = urllib.urlencode(textmod) print(textmod) #輸出內容:password=admin&user=admin req = urllib2.Request(url = '%s%s%s' % (url,'?',textmod)) res = urllib2.urlopen(req) res = res.read() print(res) #輸出內容:登錄成功?
?
其他,未測
1. GET方法
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# File: http_get.py
import urllib2
def http_get():
? ? url='http://192.168.1.13:9999/test' ? #頁面的地址
? ? response = urllib2.urlopen(url) ? ? ? ??#調用urllib2向服務器發送get請求
? ? return response.read() ? ? ? ? ? ? ? ? ? ? #獲取服務器返回的頁面信息
? ??
ret = http_get()
print("RET %r" % (ret))
?
?
3. PUT方法
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# File: http_put.py
import urllib2
import json
def http_put():
? ? url='http://192.168.1.13:9999/test'
? ? values={'':''}
? ? jdata = json.dumps(values) ? ? ? ? ? ? ? ? ?# 對數據進行JSON格式化編碼
? ? request = urllib2.Request(url, jdata)
? ? request.add_header('Content-Type', 'your/conntenttype')
? ? request.get_method = lambda:'PUT' ? ? ? ? ? # 設置HTTP的訪問方式
? ? request = urllib2.urlopen(request)
? ? return request.read()
resp = http_put()
print resp
?
?
4. DELETE方法
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# File: http_delete.py
import urllib2
import json
def http_delete():
? ? url='http://192.168.1.13:9999/test'
? ? values={'user':'Smith'}
? ? jdata = json.dumps(values)
? ? request = urllib2.Request(url, jdata)
? ? request.add_header('Content-Type', 'your/conntenttype')
? ? request.get_method = lambda:'DELETE' ? ? ? ?# 設置HTTP的訪問方式
? ? request = urllib2.urlopen(request)
? ? return request.read()
resp = http_delete()
print resp
總結
以上是生活随笔為你收集整理的python2 http请求post、get的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Redis 与 key 相关的常用命令
- 下一篇: 二、进程管理