接受请求报头是“Accept request headers”;text/html,application/xhtm..


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

我已经建立了一个完全工作的API,我建立的zf2客户端在理论上工作,但无论如何,我似乎无法从我的客户端向API发送JSON请求。每当我测试它时,我都会得到以下标题,这些标题依次返回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

现在,这是我为此使用的类,下面是我的请求设置方法。我已经做了一些尝试来获得头球,但它们都不起作用,我不知道为什么。正如我所说的,我使用的API通常会返回一个非常好的json脚本,但现在看来,头部使我无法获得必要的信息。

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;
    }
}

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

406响应代码表示您发出的请求具有服务器无法满足的Accept标头。

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

Accept: application/json

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

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中向请求添加头的问题。你可以做的是这样尝试一次:

// 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);

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