簡體   English   中英

通過php將數據請求發送到flask API

[英]Send data request by php to flask API

我正在嘗試通過自制的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?

$req = $http({method: 'get',url: "https://**.pythonanywhere.com/123",params: {mytext: "test"});

現在mytext變成了字符串,您沒有將它作為字符串傳遞。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM