本文共 1420 字,大约阅读时间需要 4 分钟。
代码如下:
#!/noah/bin/python3 -u# -*- coding: utf-8 -*-#read from mysql based on dist-id, then get enough info send to ccsimport subprocessimport sysimport jsonimport osimport urllib.parseimport urllib.requestimport base64#/home/users/liyong14/work/bin/python3url = '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('', 'foo=bar')应该变成:request = urllib.request.Request('', 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)
2)
3)
转载地址:http://qzoqj.baihongyu.com/