当我在 zf2 客户端代码中想要 "application/json" 时,接受请求 headers 是 "text/html,application/xhtm ...(etc)"

Accept request headers are "text/html,application/xhtm ...(etc)" when I want "application/json" in zf2 client code

我已经设置了一个完全可用的 API,我设置的 zf2 客户端在理论上可以工作,但无论如何,我似乎无法发送 JSON我的客户向 API 提出的请求。每当我测试它时,我都会不断收到以下 headers,这又 return 一个 406 错误:

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.5
Connection: keep-alive
Host: zf2-client.local
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:43.0) Gecko/20100101 Firefox/43.0 FirePHP/0.7.4
x-insight: activate

现在这是我为此使用的class,以下是我的请求设置方法。我已经做了一些试验以将 headers 放入其中,但它们就是不起作用,我也不知道为什么。正如我所说 API 我通常使用 return 一个非常好的 json 脚本,但现在看来 headers 让我无法获得必要的信息。

protected static function doRequest($url, array $postData = null, $method = Request::METHOD_GET)
{
    $client = self::getClientInstance();
    $client->setUri($url);
  /*
 Third attempt Also Didn't work

 $client
     ->setHeaders([
     'Content-Type' => 'application/json',
     ])
     ->setOptions(['sslverifypeer' => false])
     ->setMethod('POST')
     ->setRawBody(Json::encode($params));
   */
  $client->setMethod($method);


  /* 
 seccond attempt still not working

 $client->setHeaders(array(
 Zend\Http\Header\Accept::fromString('Accept: application/json'),
 'Accept-Encoding' => 'json',
 'X-Powered-By: Zend Framework',
 ));
  */

  //first attempt at adding a working application/json header      
  // $acceptHeader = Zend\Http\Header\Accept::fromString('Accept: application/json');
  //$client->getHeaders()->addHeader($acceptHeader);

    if ($postData !== null) {
        $client->setParameterPost($postData);
    }

    $response = $client->send();

    if ($response->isSuccess()) {
        return JsonDecoder::decode($response->getBody(), Json::TYPE_ARRAY);
    } else {
        $logger = new Logger;
        $logger->addWriter(new Stream('data/logs/apiclient.log'));
        $logger->debug($response->getBody());
        return FALSE;
    }
}

欢迎任何帮助。感谢您的时间和努力:)

The 406 response code 表示您已发出服务器无法满足的 Accept header 请求。

由于您使用的 Rest API 提供 json 响应,您很可能需要发送包含 application/json 媒体的 Accept header类型:

Accept: application/json

或者将其添加到您当前接受的媒体类型列表中header。

Accept: application/json,text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

由于您没有提供有关您客户的任何详细信息,我无法进一步帮助您。将所有相关详细信息添加到您的问题以获得完整答案非常重要。如果您使用 XMLHttpRequest:

我可以举个例子
var xhr = new XMLHttpRequest();
xhr.setRequestHeader ("Accept", "application/json");

您也可以在 PostMan.

等工具中对此进行测试

更新:

我注意到在 ZF2 中向请求添加 header 时出现的问题与您的类似。 你可以做的是像这样尝试一次:

// get the headers from your client
$headers = $client->getHeaders();
// add the new accept header
$headers->addHeader($acceptHeader);
// set new headers object with the added accept header.
$client->setHeaders($headers);

我不得不同意对你的问题的评论,你正在处理的这个请求似乎来自浏览器而不是你的客户端 object。如果是这种情况,您应该在浏览器端添加 accept-header。