1. 程式人生 > >python http協議程式碼

python http協議程式碼

傳送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