由于我的IP没有改变,因此在尝试访问google books api时三天内收到上述错误消息。我可以在命令行上用简单的方法重现它
curl "https://www.googleapis.com/books/v1/volumes?q=frankenstein"
所以这不是我的代码。可以修复添加国家/地区代码:
curl "https://www.googleapis.com/books/v1/volumes?q=frankenstein&country=DE"
现在我如何在PHP客户端中执行此操作?
我尝试添加country作为可选参数:
$client = new Google_Client();
$client->setApplicationName("My_Project");
$client->setDeveloperKey( $google_books_api_key );
$service = new Google_Service_Books($client);
$optParams = array(
'country' => 'DE'
);
$results = $service->volumes->listVolumes($terms, $optParams);
但那只是给了我
{"error": {"errors": [{"domain": "global","reason": "backendFailed","message": "Service temporarily unavailable.","locationType": other","location": "backend_flow"}],"code": 503,"message": "Service emporarily anavailable."}}
我发现某个地方将用户IP设置为我有权访问的解决方案仍然给了我“地理限制”错误消息。
$optParams = array(
'userIp' => '91.64.137.131'
);
我为PHP之外的客户找到了解决方案,如Java?或Ruby或C#,但它们似乎对我没有帮助。
在PHP客户端中,一个setCountry($ country)方法存在于'class Google_Service_Books_VolumeAccessInfo extends Google_Model'中,但我不知道如何访问该方法。有谁知道如何解决这个问题?
您可以采用与使用中间件共享的其他语言示例类似的方式完成此操作:
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Uri;
use GuzzleHttp\Middleware;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Handler\CurlHandler;
// Set this value to the country you want.
$countryCode = 'DE';
$client = new Google_Client();
$client->setApplicationName("My_Project");
$client->setDeveloperKey( $google_books_api_key );
$service = new Google_Service_Books($client);
$optParams = [];
$handler = new CurlHandler;
$stack = HandlerStack::create($handler);
$stack->push(Middleware::mapRequest(function ($request) use ($countryCode) {
$request = $request->withUri(Uri::withQueryValue(
$request->getUri(),
'country',
$countryCode
));
return $request;
}));
$guzzle = new Client([
'handler' => $stack
]);
$client->setHttpClient($guzzle);
$results = $service->volumes->listVolumes($terms, $optParams);
中间件是一组用于修改请求和响应的函数。此示例添加了一个请求中间件,在分派请求之前,会将country=$countryCode
添加到URI查询字符串中。
这个例子在某种程度上被简化了,你需要对它进行一些处理。最大的问题是,这个中间件会将国家代码添加到从这个Google_Client
实例发送的每个请求中。我建议添加额外的逻辑来限制对此请求的修改。