在php中发送浮点数作为HTTP POST请求

时间:2015-10-15 04:59:23

标签: php http

我正在编写一个由客户端执行的脚本,它将生成一个浮点数组(我在PHP中理解它应该与双精度数相同)并对一个页面执行一个post请求,该页面将获取数据和计算均值,在响应中返回该数据。我的计划是以json格式附加在消息体中发送数组。我在网上找到了一个在PHP中执行POST请求的教程,我从中获取了函数do_post_request(),我无法解决以下异常:

PHP Fatal error:  Uncaught exception 'Exception' with message 'Problem with http://localhost/average.php' in /home/yak/restclient.php:20
Stack trace:
#0 /home/yak/restclient.php(5): do_post_request('http://localhos...', '[1.5,1.5,1.5,1....', 'Content-Type=ap...')
#1 {main}
    thrown in /home/yak/restclient.php on line 20

客户端代码:

<?php
$array = array_fill(0,5,1.5);
$data = json_encode($array);
echo $data;
$response = do_post_request("http://localhost/average.php",$data,"Content-Type=application/json");
echo $response;

function do_post_request($url, $data, $optional_headers = null)
{
  $params = array('http' => array(
              'method' => 'POST',
              'content' => $data
            ));
  if ($optional_headers !== null) {
    $params['http']['header'] = $optional_headers;
  }
  $ctx = stream_context_create($params);
  $fp = @fopen($url, 'r', false, $ctx);
  if (!$fp) {
    throw new Exception("Problem with $url");
  }
  $response = @stream_get_contents($fp);
  if ($response === false) {
    throw new Exception("Problem reading data from $url);
  }
  return $response;
}
?>

是否有人能够对这个错误有所了解,或者更好的是,建议一个更好的方法来做我在这里尝试做的事情?我也尝试使用http_post_data()函数,但即使尝试在SO上找到一些修复,我也无法使它工作(PHP将其视为未定义的函数)。

这是服务器代码:

<?php
header("Content-Type:application/json");
if(!empty($_POST['data'])) {
#calculate mean of each array and send results
    $data = $_POST['data'];
    $array = json_decode($data);
    $mean = array_sum($array)/count($array);
    respond(200,"OK",$mean);
} else {
#invalid request
    respond(400,"Invalid Request",NULL);
}
function respond($status,$message,$data) {
    header("HTTP/1.1 $status $message");
    $response['status']=$status;
    $response['message']=$message;
    $response['data']=$data;
    $json_response=json_encode($response);
    echo $json_response;
}
?>

这最终将适用于处理在一条消息中发送的几个数组,但是为了开始我认为这很简单 - 我错了。

更新:使用Arpita的回答,请求现在正在通过,但响应表明请求无效,就好像它实际上没有进行POST一样。

2 个答案:

答案 0 :(得分:1)

尝试使用Curl

Content-Length

请注意$feed = http://some.url/goes/here $ch = curl_init($feed); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json')); echo $result = curl_exec($ch); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));替换为您的输出格式。

答案 1 :(得分:1)

与其他答案几乎相同,我会使用cURL并调用此函数,就像您已经这样做,但在可选标题中使用:代替= 作为数组

客户端

<?php
// $url is a string with the URL to send the data to
// $data is an associative array containing each value you want to send through POST, for example: array( 'data', json_encode($array, TRUE) );
// $optional_headers is a normal array containing strings (key:value, using ":" instead of "="), for example: array( 'Content-Type: application/json' );

function do_post_request($url, $data, $optional_headers)
{
    $ch = curl_init( $url );

    curl_setopt( $ch, CURLOPT_POST, TRUE ); // People usually use count($data) or even just 1 instead of TRUE here, but according to the documentation, it should be TRUE (any number greater than 0 will evaluate to TRUE anyway, so it's your personal call to use one or another)
    curl_setopt( $ch, CURLOPT_POSTFIELDS, serialize($data) );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, TRUE );
    curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, TRUE ); // Not harmful, will follow Location: header redirects if the server sends them
    curl_setopt( $ch, CURLOPT_HTTPHEADER, $optional_headers );

    return curl_exec( $ch );
}


$array = array_fill(0,5,1.5);
$data = json_encode($array);
echo $data;
$response = do_post_request("http://localhost/average.php", $data, array('Content-Type: application/x-www-form-urlencoded', 'Accept: application/json')); // Note the difference: Content-Type says what you are SENDING, Accept is what you will ACCEPT as an answer. You're sending an encoded JSON inside a usual FORM format, so your Content-Type will be an HTML FORM format instead of a JSON one (in other words: you're sending a STRING that represents the JSON inside a FORM ARRAY)
echo $response;

?>

为了澄清最后一点(带有Content-Type的可选标头),当你说Content-Type: application/json你应该发送一个JSON字符串时,我的意思是,例如:

[1, 2, 5, 3, 4](POST网址编码为:%5B1%2C+2%2C+5%2C+3%2C+4%5D

但你实际上发送了这个(Content-Type: application/x-www-form-urlencoded):

data=[1, 2, 5, 3, 4](POST网址编码为:data=%5B1%2C+2%2C+5%2C+3%2C+4%5D

application/x-www-form-urlencoded接受键值对,就像GET URL中的键值对一样。