【问题标题】:Send data request by php to flask API通过php向flask API发送数据请求
【发布时间】:2018-07-26 11:38:43
【问题描述】:

我正在尝试通过自制 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 工作?

【问题讨论】:

    标签: php python python-3.x api flask


    【解决方案1】:
    $req = $http({method: 'get',url: "https://**.pythonanywhere.com/123",params: {mytext: "test"});
    

    现在mytext 变成了字符串,你没有将它作为字符串传递。

    【讨论】:

    • 我编辑了问题,我也尝试了字符串,但它不起作用
    猜你喜欢
    • 1970-01-01
    • 2018-04-12
    • 2020-10-07
    • 2021-09-19
    • 2012-03-15
    • 2017-09-14
    • 1970-01-01
    • 2016-01-25
    • 2016-04-05
    相关资源
    最近更新 更多