代碼如下:
#!/noah/bin/python3 -u
# -*- coding: utf-8 -*-
#read from mysql based on dist-id, then get enough info send to ccs
import subprocess
import sys
import json
import os
import urllib.parse
import urllib.request
import base64
#/home/users/liyong14/work/bin/python3
url = 'http://localhost:8921/megacorp/employee/2'
url = 'http://localhost:8509/datadist/api/TestGroup_success'
param_data = {
"first_name": "nick",
"last_name" : "nick",
"last_name" : "liyong",
"age" : 25,
"about" : "HAHA",
"interests" : "sports,music",}
data = {
"data":json.dumps(param_data)
}
param = urllib.parse.urlencode(data, encoding='UTF-8')
param_value = param.encode(encoding='UTF-8')
print(param_value)
try:
ret = urllib.request.Request(
url,
param_value,
)
#ret.add_header("")
responseData = urllib.request.urlopen(ret).read().decode('utf-8')
except Exception as err:
print("errmsg is " + str(err))
print(responseData)
1)The POST data should be bytes,即通過post請求發送的數據應該是bytes類型:
如果請求是:
request = urllib.request.Request('http://does.not.matter', 'foo=bar') 應該變成: request = urllib.request.Request('http://does.not.matter', b'foo=bar') 這樣Python會自動計算本次請求的Content-length : mv = memoryview(data) Content-length = len(mv) * mv.itemsize
2)data should be a buffer in the standard application/x-www-form-urlencoded format:post的數據應該進行url-encode處理
通日誌可以看到,http的http_agent是:Http_agent:Python-urllib/3.4
參考:
1)http://bugs.python.org/issue11082
2)http://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3
3)https://docs.python.org/3.2/library/urllib.request.html#module-urllib.request