我试图通过自制的Flask API发送数据。 这是我的api代码:
def add_message(uuid):
content = request.json
try:
print(content['mytext'])
except:print(content)
return jsonify({"uuid":uuid})
if __name__ == '__main__':
app.run(debug=True)
如果我通过python发送数据,一切正常:
res = requests.get('https://**.pythonanywhere.com/123', json={"mytext":"test"})
if res.ok:
print( res.json())
但如果我使用php:
$host = "https://**.pythonanywhere.com";
$url = $host.'/1237R4';
echo http($url,json_encode([
"mytext"=>"python rules"
]),'post');
function http($url,$data=[],$method='get'){
$ch = curl_init();
$chOpts = [
CURLOPT_SSL_VERIFYPEER=>false,
CURLOPT_HEADER=>false,
CURLOPT_FOLLOWLOCATION=>true,
CURLOPT_RETURNTRANSFER=>true,
CURLOPT_CONNECTTIMEOUT =>8,
CURLOPT_TIMEOUT => 16,
CURLOPT_HTTPHEADER,[
'Content-Type: application/json'
]
];
if($method=='post'){
$chOpts[CURLOPT_POST]=true;
$chOpts[CURLOPT_POSTFIELDS]=$data;
$chOpts[CURLOPT_URL]=$url;
}
else{
$url.='?'.is_array($data)?http_build_query($data):$data;
$chOpts[CURLOPT_URL]=$url;
}
echo 'Request: '.$method.'['.$url.']'."\n";
print_r($data);
curl_setopt_array($ch, $chOpts);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
我在日志中遇到以下错误:
[b'{"ok":false,"error_code":400,"description":"Bad Request: message text is empty"}']
如何让它适用于php?
答案 0 :(得分:0)
$req = $http({method: 'get',url: "https://**.pythonanywhere.com/123",params: {mytext: "test"});
现在mytext
变成了字符串,你没有将它作为字符串传递。