[英]curl json with python to php
i got problems in sending a json over curl to php.我在通过 curl 向 php 发送 json 时遇到问题。 from php to php it justs works fine...从 php 到 php 它工作正常......
client side (python):客户端(python):
def sendAlivePing():
value = time.strftime('%Y-%m-%d %H:%M:%S')
if(debug=="true"):
print"alive ping: ",value
try:
#update
import requests
url = 'xxx/xchange_server.php'
payload = {'operation':'update',
'service':'ip',
'data':{'sqltable':'xxx',
'default_ip':'xxx',
'vpn_ip':'xxx',
'name':'xxx'
}}
headers = {'content-type': 'application/json'}
r = requests.post(url, data=payload, headers=headers)
print r
except:
pass
Debugging information:调试信息:
The response should be a string from a test echo.响应应该是来自测试回显的字符串。
on client side:在客户端:
print r.content
print r.raw
print r.url
print r.headers.get('content-type')
print r
Result on client side:客户端结果:
NULL
<urllib3.response.HTTPResponse object at 0xb5d5a310>
xxxx.php
text/html
<Response [200]>
It seems my json goes not through the curl or not in the correct format....看来我的 json 没有通过 curl 或格式不正确....
My curl data which works in php:我的 curl 数据适用于 php:
// API URL
$url = 'xxx/xchange_server.php';
// Create a new cURL resource
$curl = curl_init($url);
// Setup request to send json via POST
//**EXAMPLE** IP Update
$data = array(
'operation' => 'update',
'service' => 'ip',
'data' => array(
'sqltable' => 'xxx',
'default_ip' => 'xxx',
'vpn_ip' => 'xxx',
'name' => 'xxx'
),
);
// Attach encoded JSON string to the POST fields
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
// Set the content type to application/json
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
// Return response instead of outputting
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Set the CURLOPT_POST option to true for POST request
curl_setopt($curl, CURLOPT_POST, true);
// Execute cURL request and getting response
$response = curl_exec($curl);
// Close cURL resource
curl_close($curl);
// Display response
//echo htmlentities($response);
//load response into variables
$values = explode(' ', $response);
//var_dump($values);
echo $values[0];
//echo $values[1];
echo PHP_EOL;
Have you tried passing the data as a JSON string instead of a dictionary into the request?您是否尝试将数据作为 JSON 字符串而不是字典传递到请求中?
import json
# your code
r = requests.post(url, data=json.dumps(payload), headers=headers)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.