繁体   English   中英

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

[英]Send array of floats as HTTP POST request in php

我正在编写要由客户端执行的脚本,该脚本将生成一个浮点数组(我理解在PHP中应该与double相同),并向页面执行发布请求,该请求将获取数据并计算均值,并在响应中返回该数据。 我的计划是将数组以json格式附加在消息正文中。 我在网上找到了一个使用PHP执行POST请求的教程,该教程使用了do_post_request()函数,但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。

尝试改用卷曲

$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')); 用您的输出格式替换'Accept: application/json'

与其他答案几乎相同,我将使用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] %5B1%2C+2%2C+5%2C+3%2C+4%5D [1, 2, 5, 3, 4] (POST URL编码为: %5B1%2C+2%2C+5%2C+3%2C+4%5D

但是,您实际上是在发送此消息(它是Content-Type: application/x-www-form-urlencoded ):

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

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

暂无
暂无

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

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