使用wklej API生成短链接时POST请求报错求助
解决wklej.to API链接缩短的参数缺失问题
我尝试通过wklej.to的API缩短链接,但该网站仅提供PHP版文档,无法自行排查问题。官方给出的示例请求如下:
https://wklej.to/api/url/add $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "https://wklej.to/api/url/add", CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 2, CURLOPT_TIMEOUT => 10, CURLOPT_FOLLOWLOCATION => true, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_HTTPHEADER => array( "Authorization: Bearer HERE IS MY API KEY", "Content-Type: application/json", ), CURLOPT_POSTFIELDS => '{ "url": "https:\/\/google.com", "custom": "google", "password": "mypass", "expiry": "2020-11-11 12:00:00", "type": "splash", "metatitle": "Not Google", "metadescription": "Not Google description", "metaimage": "https:\/\/www.mozilla.org\/media\/protocol\/img\/logos\/firefox\/browser\/og.4ad05d4125a5.png", "geotarget": [ { "location": "Canada", "link": "https:\/\/google.ca" }, { "location": "United States", "link": "https:\/\/google.us" } ], "devicetarget": [ { "device": "iPhone", "link": "https:\/\/google.com" }, { "device": "Android", "link": "https:\/\/google.com" } ], "languagetarget": [ { "language": "en", "link": "https:\/\/google.com" }, { "language": "fr", "link": "https:\/\/google.ca" } ], "parameters": [ { "name": "aff", "value": "3" }, { "device": "gtm_source", "link": "api" } ] }', )); $response = curl_exec($curl); curl_close($curl); echo $response;
第一次尝试的错误
我最初用Python发送了如下请求:
r = requests.post("https://wklej.to/api/url/add", data = {"api": "HERE IS MY API KEY", "url": "https://amazon.com"})
收到的响应是:
{"error":1,"message":"A valid API key is required to use this service."}
我刚学Python,推测需要发送JSON格式的请求,而且API文档说明只需指定待缩短链接和API密钥,其余为可选参数。
更新后的问题
调整请求后代码如下:
headers = { 'Authorization': 'Bearer MY_API_KEY', 'Content-Type': 'application/json', } data = {"url": "https://amazon.com"} r = requests.post("https://wklej.to/api/url/add", headers=headers, data=data)
但响应还是报错:
{"error":1,"message":"Missing required parameter: url"}
明明已经在data里设置了url,为什么还提示缺少这个参数?
解决方案
问题出在requests.post的参数使用上:
- 当你用
data参数传入字典时,requests默认会把数据编码成application/x-www-form-urlencoded格式(表单格式),但API期望的是application/json格式的请求体。 - 正确的做法是使用
json参数代替data,requests会自动把字典序列化成JSON字符串,并设置正确的Content-Type(你手动设置的header也可以保留)。
修正后的代码:
headers = { 'Authorization': 'Bearer MY_API_KEY', } data = {"url": "https://amazon.com"} r = requests.post("https://wklej.to/api/url/add", headers=headers, json=data)
如果你坚持用data参数,需要手动把字典转成JSON字符串:
import json headers = { 'Authorization': 'Bearer MY_API_KEY', 'Content-Type': 'application/json', } data = json.dumps({"url": "https://amazon.com"}) r = requests.post("https://wklej.to/api/url/add", headers=headers, data=data)
这样API就能正确识别到url参数了。
内容的提问来源于stack exchange,提问作者Koke
相关产品推荐
相关产品推荐

