PHP API发送POST请求

时间:2016-04-27 22:05:40

标签: php

我有这个连接到外部API的函数:

function ICUK_Request($url, $method = 'GET', $body = NULL) {
        $client = new IcukApiClient();
        $client->username = "user";
        $client->key = "pass";
        $client->encryption = "SHA-512";

        $req = new IcukApiRequest();
        $req->url = $url;
        $req->method = $method;

        if(!is_null($body)) {
            $req->body = $body;
        }

        $res = $client->send($req);
        if ($res->success) {
            $obj = json_decode($res->response);
        }
        else {
            throw new Exception('There was an error contacting the API.');
        }

        return $obj;
    }

API文档告诉我发送POST请求,如下所示:

POST /domain/registration/new/
{
   "domain_name": "domain.co.uk",
   "hosting_type": "NONE",
   "registration_length": 1,
   "auto_renew": false,
   "domain_lock": false,
   "whois_privacy": false,
   "contact_registrant_id": 1
}

所以我试过这个:

$arr = array(
    "domain_name" => "domain.co.uk",
   "hosting_type" => "NONE",
   "registration_length" => 1,
   "auto_renew" => false,
   "domain_lock" => false,
   "whois_privacy" => false,
   "contact_registrant_id" => 1
);

ICUK_Request("/domain/registration/new", "POST", $arr);

但那可以在API日志中给我一个回复说:

{
  "exception_message": "Internal API exception occured",
  "exception_type": "InternalApiException"
}

我不确定这是否是通用的,如果有人可以帮助如何发布数据?

1 个答案:

答案 0 :(得分:2)

以json发送:

$values = json_encode($arr);
ICUK_Request("/domain/registration/new", "POST", $values);