使用Google Books API的WP_REMOTE_GET

时间:2013-02-07 作者:sosukeinu

我试图从谷歌API中获取一些信息,但遇到了一些麻烦。我的代码:

$body = array(
    \'intitle\' => \'Test\', //Returns results where the text following this keyword is found in the title.
    \'inauthor\' => \'\',  //Returns results where the text following this keyword is found in the author.
    \'inpublisher\' => \'\',  //Returns results where the text following this keyword is found in the publisher.
    \'key\' => \'\', //API key
    \'subject\' => \'\', //Returns results where the text following this keyword is listed in the category list of the volume.
    \'isbn\' => \'\',  //Returns results where the text following this keyword is the ISBN number.
    \'lccn\' => \'\',  //Returns results where the text following this keyword is the Library of Congress Control Number.
    \'oclc\' => \'\'  //Returns results where the text following this keyword is the Online Computer Library Center number.
);

$args = array(
    \'body\' => $body,
    \'timeout\' => \'5\',
    \'redirection\' => \'5\',
    \'httpversion\' => \'1.0\',
    \'blocking\' => true,
    \'headers\' => array(),
    \'cookies\' => array()
);

$response = wp_remote_get( \'https://www.googleapis.com/books/v1/volumes?q=search+terms\', $args );

if( is_wp_error( $response ) ) {
   $error_message = $response->get_error_message();
   echo "Something went wrong: $error_message";
} else {
   echo \'Response:<pre>\';
   print_r( $response );
   echo \'</pre>\';
}
这始终返回400错误。如果我把我的$body 它完美返回的数组(albiet没有任何自定义参数)。以下是Google生成的错误:

Array
(
    [headers] => Array
        (
            [content-type] => text/html; charset=UTF-8
            [content-length] => 925
            [date] => Thu, 07 Feb 2013 15:09:24 GMT
            [server] => GFE/2.0
        )

    [body] => 





  Google


400. That’s an error.

Your client has issued a malformed or illegal request. That’s all we know. [response] => Array ( [code] => 400 [message] => Bad Request ) [cookies] => Array ( ) [filename] => ) 
以下是正确返回的示例:

Array
(
    [headers] => Array
        (
            [expires] => Thu, 07 Feb 2013 15:20:03 GMT
            [date] => Thu, 07 Feb 2013 15:20:03 GMT
            [cache-control] => private, max-age=0, must-revalidate, no-transform
            [etag] => "oJJnsPwmwzPHUK-6EQKPiLmyEMg/ZaxtQy3hi8hix-i3y1_kfXYZAVA"
            [content-type] => application/json; charset=UTF-8
            [x-content-type-options] => nosniff
            [x-frame-options] => SAMEORIGIN
            [x-xss-protection] => 1; mode=block
            [server] => GSE
        )

    [body] => {
 "kind": "books#volumes",
 "totalItems": 1433,
 "items": [
  {
   "kind": "books#volume",
   "id": "tskCFsTjsnkC",
   "etag": "0o/Hdha/+K0",
   "selfLink": "https://www.googleapis.com/books/v1/volumes/tskCFsTjsnkC",
   "volumeInfo": {
    "title": "The Everything Word Search Book",
    "subtitle": "Over 250 Puzzles to Keep You Entertained for Hours!",
    "authors": [
     "Charles Timmerman"
    ],
    "publisher": "Adams Media",
    "publishedDate": "2005-11-15",
    "description": "With more than 250 puzzles, 100-plus more than our competition, The Everything(r) Word Search Book provides hours of gaming fun! Searches are organized by amusing themes, including: Work Searches on the Job Global Word Searches Word Searches Alive! Word Searches for Big Bucks Decades of Word Searches to Search or Not to Search? The Everything(r) Word Search Book is sure to excite gamers of all abilities with humorous and challenging puzzles.",
    "industryIdentifiers": [
     {
      "type": "ISBN_10",
      "identifier": "1593374313"
     },
     {
      "type": "ISBN_13",
      "identifier": "9781593374310"
     }
    ],
    "pageCount": 304,
    "printType": "BOOK",
    "categories": [
     "Games"
    ],
    "averageRating": 4.0,
    "ratingsCount": 3,
    "contentVersion": "1.3.3.0.preview.3",
    "imageLinks": {
     "smallThumbnail": "http://bks0.books.google.com/books?id=tskCFsTjsnkC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api",
     "thumbnail": "http://bks0.books.google.com/books?id=tskCFsTjsnkC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
    },
    "language": "en",
    "previewLink": "http://books.google.com/books?id=tskCFsTjsnkC&printsec=frontcover&dq=search+terms&hl=&cd=1&source=gbs_api",
    "infoLink": "http://books.google.com/books?id=tskCFsTjsnkC&dq=search+terms&hl=&source=gbs_api",
    "canonicalVolumeLink": "http://books.google.com/books/about/The_Everything_Word_Search_Book.html?hl=&id=tskCFsTjsnkC"
   },
   "saleInfo": {
    "country": "US",
    "saleability": "FOR_SALE",
    "isEbook": true,
    "listPrice": {
     "amount": 14.95,
     "currencyCode": "USD"
    },
    "retailPrice": {
     "amount": 9.99,
     "currencyCode": "USD"
    },
    "buyLink": "http://books.google.com/books?id=tskCFsTjsnkC&dq=search+terms&hl=&buy=&source=gbs_api"
   },
   "accessInfo": {
    "country": "US",
    "viewability": "PARTIAL",
    "embeddable": true,
    "publicDomain": false,
    "textToSpeechPermission": "ALLOWED",
    "epub": {
     "isAvailable": true
    },
    "pdf": {
     "isAvailable": true.....
非常感谢您提供的任何帮助。

1 个回复
最合适的回答,由SO网友:Wyck 整理而成

我很确定您必须将关键字或搜索词直接添加到查询中,例如:

$key = \'flowers\'; // search for word flowers in book titles.

// fill rest in as you desire
$args = array(
     \'timeout\' => \'5\',
     \'redirection\' => \'5\',
     \'sslverify\' => false // for localhost
);

//check for titles using +intitle
$response = wp_remote_get( \'https://www.googleapis.com/books/v1/volumes?q=\'. $key . \'+intitle\', $args );
这将返回:

  "kind": "books#volumes",
     "totalItems": 795,
      //...etc etc

      \'response\' => 
    array
      \'code\' => int 200
     //etc etc..
不知道API有多准确,因为返回的第一本书的标题中显然没有flowers这个词,它返回了“Encyclopedia Britannica”,但我没有阅读API文档。

此外,为了更好地快速调试,请将其放入插件或functions.php:

add_action( \'http_api_debug\', \'viper_http_api_debug\', 10, 5 );

function viper_http_api_debug( $response, $type, $class, $args, $url ) {
    // You can change this from error_log() to var_dump() but it can break AJAX requests
    var_dump( \'Request URL: \' . var_export( $url, true ) );
    var_dump( \'Request Args: \' . var_export( $args, true ) );
    var_dump( \'Request Response : \' . var_export( $response, true ) );
}

结束

相关推荐