错误的json数组Python向PHP发布请求

时间:2020-12-05 16:55:59

I'm trying to send a post request with Python to PHP (I'm using Phalcon PHP).

我正在尝试用Python发送一个post请求到PHP(我正在使用Phalcon PHP)。

Python Code:

array_hash =["0x348eb29f3295fedc10b5b869c751fb5479585c7e65169512c3a5ff474bc0e85a", "0x63b2590119f7ea533ed93e6b2e6112410fbf49f99157bc6d7e0ce7469d3d23a8", "0xfbcdc555a3783b5cfa495ad7a5d14a159657a3f0f6b6a68583fb06ebdf984d70"]

json_data = json.dumps({"data_hash": array_hash})

requests.post(php_url, json=json_data)

My Python print array is good, I have this :

我的Python打印数组很好,我有这个:

{  
   "data_hash":[  
      "0x348eb29f3295fedc10b5b869c751fb5479585c7e65169512c3a5ff474bc0e85a",
      "0x63b2590119f7ea533ed93e6b2e6112410fbf49f99157bc6d7e0ce7469d3d23a8",
      "0xfbcdc555a3783b5cfa495ad7a5d14a159657a3f0f6b6a68583fb06ebdf984d70"
   ]
}

But now when I'm trying to get it with PHP my array is empty and when I make a loop on the array I have this error :

但现在当我试图用PHP获取它时,我的数组是空的,当我在数组上进行循环时,我有这个错误:

Invalid argument supplied for foreach() 

Here is my PHP code :

这是我的PHP代码:

if($this->request->isPost()){
    error_log($this->request->getPost('data_hash')[0]);
    foreach ($this->request->getPost('data_hash') as $value) {
        error_log($value);
    }
}

But when I send just json string like this :

但是当我发送像这样的json字符串时:

{"test1": "hello", "test2": "world"}

I can get it in PHP and it works. So... What is wrong with my Python array ?

我可以用PHP获得它,它的工作原理。那么......我的Python数组出了什么问题?

1 个解决方案

#1


1  

You may need to use data instead of json argument with headers argument as well:

您可能还需要使用数据而不是json参数和headers参数:

requests.post(php_url, data=json_data, headers={'Content-Type': 'application/json', 'Accept':'application/json'})

Take a look at this in requests documentation More complicated POST requests

在请求文档中查看此更复杂的POST请求

In your PHP code you need to use the following: (as your request specifies json for the content type)

在您的PHP代码中,您需要使用以下内容:(因为您的请求为内容类型指定了json)

$rawBody = $this->request->getJsonRawBody(true);

#1


1  

You may need to use data instead of json argument with headers argument as well:

您可能还需要使用数据而不是json参数和headers参数:

requests.post(php_url, data=json_data, headers={'Content-Type': 'application/json', 'Accept':'application/json'})

Take a look at this in requests documentation More complicated POST requests

在请求文档中查看此更复杂的POST请求

In your PHP code you need to use the following: (as your request specifies json for the content type)

在您的PHP代码中,您需要使用以下内容:(因为您的请求为内容类型指定了json)

$rawBody = $this->request->getJsonRawBody(true);