python 网络请求相比Android 网络请求要简单
1,你可以定义一个自己的请求头,也可以不写。 如:
http_headers = {'Accept': 'application/json', 'Connection': 'keep-alive',
'User-Agent': 'PCHM10,PCHM10,OPPO,Android 10,WIFI'}
由于,我们公司请求User-Agent必须是手机,否则就会重定向到其它域名,所有,我写死了我的手机型号
2,你设置请求参数
apiHost = ""
appType = ""
good_app_type = ""
platform = "android"
apiKey = ""
version = ""
apiDevice = "1"
channel = "default"
# 请求打包参数
apiPullMethod = "api/v1/app_package"
# 打包成功进行上传方法
apiFinishMethod = "api/v1/articles-add-comment"
这些参数,根据公司请求约定的来填写。
3、对请求参数md5加密,公司没这要求可以不看
md5 = hashlib.md5()
t = str(int(time.time()))
# 请求参数
queryArray = {'app_type': self.appType, 'good_app_type': self.good_app_type, 'deviceid': self.apiDevice,
'platform': self.platform, 'timestrap': t, 'channel': self.channel, 'version': self.version,
'secret': "package_meite_question_secrtet", 'id': jId}
ls = sorted(queryArray)
# 排序
s = ''
for key in ls:
s += key + queryArray[key]
# 加密串拼接apiKey
md5.update((s + self.apiKey).encode('utf8'))
# 获取加密串数据 ,字典添加sign
queryArray['sign'] = md5.hexdigest()
# 重装字符串
queryString = urlencode(queryArray)
我们公司是对请求参数先排序,然后拼接apiKey ,组成加密串,进行加密
4、进行get请求
# get请求
result = requests.get(self.apiHost + self.apiPullMethod + '?' + queryString, headers=http_headers)
# print(result.content)
try:
contentJson = json.loads(result.content.decode('utf8'))
print("code=" + str(contentJson['code']))
except Exception as e:
print(e)
return []
if contentJson['code'] != 200:
return []
return contentJson['data']['data']
返回数据格式根据公司请求定义。 现在你可以进行数据操作了
5、post请求
与get请求类似
data = {'articles_id': "1", 'content': 'hhhh'}
print('finish接口上报数据')
# post请求
result = requests.post(self.apiHost + self.apiFinishMethod + '?' + queryString, data=data, headers=http_headers)
print(result)
try:
contentJson = json.loads(result.content.decode('utf8'))
print("code=" + str(contentJson['code']))
print("data=" + str(contentJson['data']))
except Exception as e:
print(e)
return []
if contentJson['code'] != 200:
return []
你需要定义data={} 传入post请求参数,最后拼接在post()方法里面
python下载地址:https://download.csdn.net/download/qq_28759359/20722066

8919

被折叠的 条评论
为什么被折叠?



