如何做一个PHP卷曲帖子

时间:2016-02-13 21:26:07

标签: php curl

我喜欢用curl发布一个JSON对象。我所拥有的只是那段代码:

data_only=True

现在该怎么做才能在PHP中实现这一目标?你能发一个例子吗?

2 个答案:

答案 0 :(得分:0)

// init curl

$handle = curl_init();

// set options/parameters

curl_setopt( $handle, CURLOPT_URL,              'https://developer.lametric.c...');
curl_setopt( $handle, CURLOPT_CUSTOMREQUEST,    "POST");
curl_setopt( $handle, CURLOPT_POSTFIELDS,       'the-json-encoded-data-here' );
curl_setopt( $handle, CURLOPT_RETURNTRANSFER,   true ); // you want to get the response

// set headers 

curl_setopt( $handle, CURLOPT_HTTPHEADER,       array(  'Accept: application/json',
                                                        '....' ) );
// execute the request and get the response

$response = curl_exec( $handle );

// get the status too

$status = curl_getinfo( $handle, CURLINFO_HTTP_CODE );

// release resources

curl_close( $handle );

只是一个例子/介绍。

你初始化了php的卷曲。

设置所有参数。

发送请求。

我不会为你写下所有代码。

PHP参考是明确的(也有例子)

http://php.net/manual/en/book.curl.php

也有例子:

PHP + curl, HTTP POST sample code?

答案 1 :(得分:0)

或者没有卷曲,我用来保持依赖关系的非常通用的模式。

<?php 

$reqBody = array(
    'frames' => array(
        'index' => 0,
        'text' => "SUCCESS",
        'icon' => null
    )
);


$bodyString = json_encode($reqBody);

$access_token = "###secureToken###";
$context_options = array (
    'http' => array (
        'method' => 'POST',
        'header' => "Accept: application/json\r\nX-Access-Token: " . $access_token . "\r\nCache-Control: no-cache\r\nContent-Length: " . strlen($bodyString) . "\r\n",
        'content' => $bodyString
        )
    );
$context_for_post = stream_context_create($context_options);

$response = file_get_contents($"https://developer.lametric.com/api/V1/dev/widget/update/com.lametric.###appid###", FALSE, $context_for_post);

// Check for errors
if(!$response){
    die("<h2>ERROR</h2>");
}

// Decode the response
$responseData = json_decode($response, TRUE);

// some examples of parsing response json ...
if ($responseData['message'] != null) {

}
$this->sessionToken = $responseData['message']['data']['results']['token'];
if($this->sessionToken === FALSE) {
    die('Failed to Parse Response');
}

?>

如果网络服务器似乎不喜欢你的帖子,它可能需要表格数据类型的POST,所以设置正文和标题如下:

$bodyString = "------WebKitFormBoundaryiAsuvpNuslAE3Kqx\r\nContent-Disposition: form-data; name=\"json\"\r\n\r\n" . 
    json_encode($reqBody) . 
    "\r\n------WebKitFormBoundaryiAsuvpNuslAE3Kqx--\r\n";

$access_token = "###secureToken###";
$context_options = array (
    'http' => array (
        'method' => 'POST',
        'header' => "X-Access-Token: " . $access_token . "\r\nCache-Control: no-cache\r\nAccept: application/json\r\nContent-Type: multipart/form-data; boundary=----WebKitFormBoundaryiAsuvpNuslAE3Kqx\r\n" . "Content-Length: " . strlen($bodyString) . "\r\n",
        'content' => $bodyString
        )
    );