1

我正在尝试发布到此Microsoft API,但出现错误 400。在使用基于浏览器的 API 测试控制台和 Postman 时工作正常,但使用下面的 PHP 代码无法正常工作。我哪里错了?

  $myObj->update->name = "API test";
  $myObj->update->qnaList->qnaId = "331";
  $myObj->update->qnaList->answer = "I have been updated";
  $myObj->update->qnaList->source = "Editorial";
  $myObj->update->qnaList->questions->add = "What is your name";
  $myObj->update->qnaList->metadata->add->name = "category";
  $myObj->update->qnaList->metadata->add->value = "personality";
  $data = json_encode($myObj);

  $url = '[https://apiurl]';
  $options = array(
    'http' => array(
    'method'  => 'PATCH',
    'content' => $data,
    'header'  => "Content-Type: application/json\r\n" .
                       "Ocp-Apim-Subscription-Key: [mykey]"
    )
  );
  $context    = stream_context_create($options);
  $result     = file_get_contents($url, false, $context);
  $response   = json_decode($result, true);
  print_r($response);
4

1 回答 1

1

您尝试发送的 JSON 正文存在问题。

这对我有用并返回 204:

<?php

$myObj->update->name = "API test";
$myObj->update->qnaList = array();
$myObj->update->qnaList[0]->qnaId = "1";
$myObj->update->qnaList[0]->answer = "I have been updated";
$myObj->update->qnaList[0]->source = "Editorial";
$myObj->update->qnaList[0]->questions->add = array();
$myObj->update->qnaList[0]->questions->add[0] = "What is your name";
$myObj->update->qnaList[0]->metadata->add = array();
$myObj->update->qnaList[0]->metadata->add[0]->name = "category";
$myObj->update->qnaList[0]->metadata->add[0]->value = "personality";
$data = json_encode($myObj);

$kbid = "<YOUR-KB-ID>";

$url = 'https://westus.api.cognitive.microsoft.com/qnamaker/v3.0/knowledgebases/' . $kbid;
$options = array(
    'http' => array(
        'ignore_errors' => true,
        'method' => 'PATCH',
        'content' => $data,
        'header' => "Content-Type: application/json\r\n" .
            "Ocp-Apim-Subscription-Key: <YOUR-KEY>\r\n"
    )
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);

$response = json_decode($result, true);

echo $response . "\r\n";
?>
于 2017-10-14T03:56:40.697 回答