简体   繁体   English

请求:在 python 发布请求中发送有效负载时出错

[英]Requests: Error sending payload in python post request

The code behaving strangely that I am unable to understand what's going on..代码表现得很奇怪,我无法理解发生了什么..

The code that works fine:工作正常的代码:

link = "https://api.luminati.io/dca/trigger_immediate?collector=XXXxxxXXXxxxXXXX" 
head = {"Authorization": "Bearer xxXXxxXXxx" ,"Content-Type": "application/json"}
data = '{"url":"https://www.practo.com/pune/doctor/XXXXXXxXXXXX"}'
res = requests.post(link, headers = head, data = data)
print("Status: "+str(res.status_code), "Message: "+res.text)

Output: Output:

Status: 202 Message: {"response_id":"z7627t1617552745375r14623bt37oo"}

But I want to load "url":"https://www.practo.com/pune/doctor/XXXXXXxXXXXX" this thing dynamically.但我想动态加载"url":"https://www.practo.com/pune/doctor/XXXXXXxXXXXX"这个东西。

url = "https://www.practo.com/pune/doctor/XXXXXXxXXXXX"
link = "https://api.luminati.io/dca/trigger_immediate?collector=XXXxxxXXXxxxXXXX" 
head = {"Authorization": "Bearer xxXXxxXXxx" ,"Content-Type": "application/json"}
data = {"url":url} 
res = requests.post(link, headers = head, data = data)
print("Status: "+str(res.status_code), "Message: "+res.text)

Output: Output:

Status: 500 Message: 'Unexpected token u in JSON at position 7'

To load data dynamically try using %s string feature, like that:要动态加载数据,请尝试使用 %s 字符串功能,如下所示:

url = "https://www.practo.com/pune/doctor/XXXXXXxXXXXX"
data = '{"url":"%s"}' % url

or you can convert dictionary entirely to str, like:或者您可以将字典完全转换为 str,例如:

import json
data = {"url":link}
res = requests.post(link, headers=head, data=json.dumps(data))

by the way, you can pass body not like data, but like json, here's documents:顺便说一句,你可以传递 body 不是像数据,而是像 json,这里的文件:

:param json: (optional) json data to send in the body of the:class: Request . :param json: (可选) json 数据发送到:class: Request的正文中。 So your request will look like:因此,您的请求将如下所示:

data = {"url":link}
res = requests.post(link, headers=head, json=data)
any_dynamic_variable='XXXXXXxXXXXX'#You can make your websit or part of the url to be dynamic
url = f'https://www.practo.com/pune/doctor/{any_dynamic}'
headers = {"Authorization": "Bearer xxXXxxXXxx" ,"Content-Type": "application/json"}
payload={
    'your_key':'your_value',
    'currancy':'CA',#<==== This is an example
}
r = requests.post(url,headers=headres,data=payload}
print(r.status_code)#check your status to be able to find the error if you have any
print(r.text)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM