參考博客:https://blog.csdn.net/chendong_/article/details/51973499python
# -*- coding:UTF-8 -*- import urllib2 response = urllib2.urlopen("https://www.baidu.com/") print response.read()
# -*- coding:UTF-8 -*- import urllib2 import urllib url = 'http://127.0.0.1:8000/login/?' para = {'name':'zhangsan','age':100} req = urllib2.Request(url + urllib.urlencode(para)) page = urllib2.urlopen(req) print page.read() # 服務器端結果:{u'name': [u'zhangsan']
# -*- coding:UTF-8 -*- import urllib2 import urllib values = {'username':'zhangsan','pwd':'123456'} data = urllib.urlencode(values) url = "http://127.0.0.1:8000/login/" request = urllib2.Request(url, data) response = urllib2.urlopen(request) print response.read()
import urllib2 import json data = { 'a': 123, 'b': 456 } headers = {'Content-Type': 'application/json'} request = urllib2.Request(url='url', headers=headers, data=json.dumps(data)) response = urllib2.urlopen(request)
# -*- coding:UTF-8 -*- import urllib2 import urllib url = 'http://127.0.0.1:8000/login/' user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' values = {"username":"1098918523@qq.com", "password":"341204baiduhi"} headers = {'User_Agent': user_agent} data = urllib.urlencode(values) request = urllib2.Request(url, data, headers) response = urllib2.urlopen(request) print response.read()
def send_put(url,values): data = { 'a': 123, 'b': 456 } headers = {'Content-Type': 'application/json'} request = urllib2.Request(url=url, headers=headers, data=json.dumps(data)) request.get_method = lambda: 'PUT' response = urllib2.urlopen(request) print response.read() if __name__=="__main__": values = {'name':'新添加組01','fid':'314'} url = "http://127.0.0.1:8000/api/operate/dept" send_put(url,values)
一、encode和unquote僅對一個字符串進行轉換json
import urllib s = '張三' s_encode = urllib.quote(s) print s_encode # 執行結果:%E5%BC%A0%E4%B8%89
#二、url unquote import urllib s = '%E5%BC%A0%E4%B8%89' s_decode = urllib.unquote(s) print s_decode # 執行結果:張三
二、urlencode api
# 一、urlencode import urllib data={"name":"張三","sex":"男"} print urllib.urlencode(data) # 執行結果:name=%E5%BC%A0%E4%B8%89&sex=%E7%94%B7 # 二、unquote解析url data = 'name=%E5%BC%A0%E4%B8%89&sex=%E7%94%B7' print urllib.unquote(data) # 執行結果:name=張三&sex=男