【问题标题】:curl json with python to phpcurl json 与 python 到 php
【发布时间】:2021-03-23 21:51:36
【问题描述】:

我在通过 curl 向 php 发送 json 时遇到问题。从 php 到 php 它工作正常...

客户端(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

调试信息:

响应应该是来自测试回显的字符串。

在客户端:

print r.content
print r.raw
print r.url
print r.headers.get('content-type')
print r

客户端结果:

NULL

<urllib3.response.HTTPResponse object at 0xb5d5a310>

xxxx.php

text/html

<Response [200]>

看来我的 json 没有通过 curl 或格式不正确....

我在 php 中工作的 curl 数据:

// 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;

【问题讨论】:

    标签: python php json curl


    【解决方案1】:

    您是否尝试过将数据作为 JSON 字符串而不是字典传递到请求中?

    import json
    # your code
    r = requests.post(url, data=json.dumps(payload), headers=headers)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-19
      • 1970-01-01
      相关资源
      最近更新 更多