0

任何人都可以提供以下帮助吗?我正在尝试向 RESTful API 发出 JSON 请求。下面的代码由 Wes Furlong 分享

该代码似乎能够很好地解码为 JSON,但作为 URL 编码字符串发送

<?php
function rest_helper($url, $params = null, $verb = 'GET', $format = 'json')
{
  $cparams = array(
    'http' => array(
      'method' => $verb,
      'ignore_errors' => true
    )
  );
  if ($params !== null) {
    $params = http_build_query($params);
    if ($verb == 'POST') {
      $cparams['http']['content'] = $params;
    } else {
      $url .= '?' . $params;
    }
  }

  $context = stream_context_create($cparams);
  $fp = fopen($url, 'rb', false, $context);
  if (!$fp) {
    $res = false;
  } else {
    // If you're trying to troubleshoot problems, try uncommenting the
    // next two lines; it will show you the HTTP response headers across
    // all the redirects:
    // $meta = stream_get_meta_data($fp);
    // var_dump($meta['wrapper_data']);
    $res = stream_get_contents($fp);
  }

  if ($res === false) {
    throw new Exception("$verb $url failed: $php_errormsg");
  }

  switch ($format) {
    case 'json':
      $r = json_decode($res);
      if ($r === null) {
        throw new Exception("failed to decode $res as json");
      }
      return $r;

    case 'xml':
      $r = simplexml_load_string($res);
      if ($r === null) {
        throw new Exception("failed to decode $res as xml");
      }
      return $r;
  }
  return $res;
}

我需要能够:

  1. 添加 application/json 的内容类型
  2. 将参数转换为 JSON

在这个环境中不能使用 curl

主要的是内容类型——目前默认为 urlencoded 任何提示或想法赞赏 - 谢谢


最近的尝试

function restHelper($url, $params = null, $verb = 'GET', $format = 'json'){
  $cparams = array(
    'http' => array(
      'method' => $verb,
      'ignore_errors' => true,
      'header' =>"Content-type: application/json \r\n"
    )
  );
  if ($params !== 'None') {
     $jparams = json_encode($params);
     if ($verb == 'POST') {
          $cparams['http']['content'] = $jparams;

        } elseif ($verb =='PUT') {
          $cparams['http']['content'] = $jparams;
        } else {
          $params = http_build_query($params);
          $url .= '?' . $params;
        }
  }

仍然无法正常工作——来自 REST IDE 的 API 测试良好似乎来自内容类型如何为 JSON 工作

4

1 回答 1

0

最后找到了一种在 scriptcase 中包含 CURL 的方法。这是有效的(原型)(感谢 Lorna Jane http://www.lornajane.net/posts/2011/posting-json-data-with-php-curl)感谢所有看过这个的人

$service_url = 'http://dev.eventplus.co.nz/api/logon';
$ch = curl_init($service_url);
$data = '[
    {
        "Header": {
            "Username": "testapi@teamprema.co.nz",
            "SessionId": "123"
        }
    },
    {
        "Config": {}
    },
    {
        "Params": {"Query": {"Password": "test12345"}}
    }
]';

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen($data))                                                                       
);   

curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$response = curl_exec($ch);
if ($response === false) {
    $info = curl_getinfo($ch);
    curl_close($ch);
    die('error occured during curl exec. Additioanl info: ' . var_export($info));
}
curl_close($ch);
print $response;
于 2013-07-05T23:27:47.250 回答