简体   繁体   English

将python请求转换为等效的PHP-cURL

[英]convert python request to PHP-cURL equivalent

I am sending a POST request to a URL. 我正在将POST请求发送到URL。 It works correctly in python but in php-curl, I always get a bad request error (ie my POST data is not as expected by the server) 它在python中正常工作,但在php-curl中,我总是收到错误的请求错误(即我的POST数据与服务器所期望的不符)

Python code: (works correctly. 200 OK) Python代码:(正常工作。200OK)

import httplib, urllib, json

def SendRequest(param1):
    url = "api.xyz.com"
    body = {"version": "1.0", "data":[{"param1":param1, "age":35}]}
    jsonBody = json.dumps(body)

    headers = {"Content-type": "application/json",
               "Accept": "application/json; charset=utf8"}
    conn = httplib.HTTPConnection(url)
    conn.request("POST", "/api/?client_id=xx-xx-xx", jsonBody, headers)
    response = conn.getresponse()

php-cURL code (does not work. 406 Bad request error) php-cURL代码(无效。406错误的请求错误)

function sendCurlRequest($param1)
{
    $payload = preparePayload($param1); 
    $url = "http://api.xyz.com/api/?client_id=xx-xx-xx"; 
    $jsonResponse = executePOSTRequest($url, $payload);
    $response = json_decode($jsonResponse);
}

function preparePayload($param1)
{
    $payload = array("version" = "1.0",
                     "data" => array(array("param1" => $param1,
                                           "age" => 35
                                          )
                                    ),
                    );

    $jsonPayload = json_encode($payload);
    return $jsonPayload;
}

function executePOSTRequest($url, $payload)
{
    $newlines = array("\r", "\n", " ");
    $url = str_replace($newlines, '', $url);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_HTTPHEADERS,array('Content-Type:application/json; Accept: application/json; charset=utf8'));

    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($ch);
}

I know there is some mistake in my use of cURL. 我知道我在使用cURL时会出错。 Please suggest. 请提出建议。

Update: Use of double array in php is because server expects the JSON string (POST payload) in this format 更新:在PHP中使用双精度数组是因为服务器希望采用这种格式的JSON字符串(POST有效负载)

{
"version": "1.0",
"data":
[{"param1":name, "age":35},{"param1":name,"age":60}]
}

In python, I am using list of dict; 在python中,我使用的是字典列表; in php I think it is array of arrays only. 在PHP中,我认为这只是数组的数组。

In a case like this, I find that it's always better to look at what goes over the wire instead of trying to puzzle out what might be wrong with the code. 在这样的情况下,我发现最好查看一下网络上的内容,而不是试图弄清楚代码可能有什么问题。

My advice: 我的建议:

  • Create a little test server using the python BaseHTTPServer and derive a class from BaseHTTPRequestHandler that doesn't do anything but provide an override of the do_POST method 使用python BaseHTTPServer创建一个小的测试服务器,并从BaseHTTPRequestHandler派生一个类,该类不执行任何操作,但提供对do_POST方法的覆盖

  • Your do_POST should just dump the headers and POST body it receives to file 您的do_POST应该只是将接收到的标头和POST正文转储到文件中

  • Point your code samples at this little test server and then diff the files that it creates. 将代码样本指向此小型测试服务器,然后比较其创建的文件。 I'm guessing that if the answer isn't immediately obvious, you'll at the very least get one or more useful clues to stomp this problem out. 我猜想,如果答案不是立即显而易见的,那么您至少会获得一个或多个有用的线索来解决这个问题。

I'm not sure if it causes your problem, but I do see a difference between the two: In the python code you send two header lines: Content-Type and Accept. 我不确定是否会导致您的问题,但是我确实看到了两者之间的区别:在python代码中,您发送了两个标题行:Content-Type和Accept。 While in the PHP code, they are a single line. 在PHP代码中,它们只是一行。

You are missing the parameter index - cURL POST fields need to be sent as a query string or as an array. 您缺少参数索引-cURL POST字段需要作为查询字符串或数组发送。

Either: 要么:

curl_setopt($ch, CURLOPT_POSTFIELDS, 'payload=' . urlencode($payload));

Or 要么

curl_setopt($ch, CURLOPT_POSTFIELDS, array('payload' => $payload));

Replace payload with the name of the parameter expected by the API to hold the JSON string. payload替换为API期望用来保存JSON字符串的参数名称。

If the endpoint API is not expecting a parameter, then it should work - it just won't appear in the POST array in your test script. 如果端点API不需要参数,则它应该起作用-它不会出现在测试脚本的POST数组中。 You can fetch the body of the POST contents using 您可以使用以下方法获取POST内容的正文

$data = file_get_contents("php://input");
var_dump($data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM