Phantomjs-customheaders-property

提供:Dev Guides
移動先:案内検索

PhantomJS-customHeadersプロパティ

customHeaders関数は、ページが発行するすべてのリクエストに対してサーバーに送信される追加のHTTPリクエストヘッダーを指定します。 デフォルト値は空のオブジェクト「\ {}」です。 ヘッダー名と値は、サーバーに送信される前にUS-ASCIIでエンコードされます。

構文

その構文は次のとおりです-

var wpage = require('webpage').create();
wpage.customHeaders = {
  //specify the headers
};

次の例は、 customHeaders プロパティの使用を示しています。

var page = require('webpage').create();
var server = require('webserver').create();
var port = 8080;

var listening = server.listen(8080, function (request, response) {
   console.log("GOT HTTP REQUEST");
   console.log(JSON.stringify(request, null, 4));
});

var url = "http://localhost:" + port + "/foo/response.php";
console.log("sending request to :" +url);
page.customHeaders = {'Accept-Language' : 'en-GB,en-US;q = 0.8,en;q = 0.6'};

//additional headers are mentioned here
page.open(url, function (status) {
   if (status !== 'success') {
      console.log('page not opening');
   } else {
      console.log("Getting response from the server:");
   }
   phantom.exit();
});

customheaderを使用した出力

上記のプログラムは、次の出力を生成します。

sending request to :http://localhost:8080/foo/response.php
GOT HTTP REQUEST {
   "headers": {
      "Accept": "text/html,application/xhtml+xml,application/xml;q = 0.9,*/*;q = 0.8",
      "Accept-Encoding": "gzip, deflate",
      "Accept-Language": "en-GB,en-US;q = 0.8,en;q = 0.6",
      "Connection": "Keep-Alive",
      "Host": "localhost:8080",
      "User-Agent": "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/538.1 (KHTML, like Gecko) PhantomJS/2.1.1 Safari/538.1"
   },
   "httpVersion": "1.1",
   "method": "GET",
   "url": "/foo/response.php"
}

上記の例では、 customheader を使用して Accept-Language を設定しており、httpヘッダーにも同じことが示されています。

カスタムヘッダーなしの出力

上記のプログラムは、カスタムヘッダーなしで次の出力を生成します。

sending request to :http://localhost:8080/foo/response.php
GOT HTTP REQUEST {
   "headers": {
      "Accept": "text/html,application/xhtml+xml,application/xml;q = 0.9,*/*;q = 0.8",
      "Accept-Encoding": "gzip, deflate",
      "Accept-Language": "en-IN,*",
      "Connection": "Keep-Alive",
      "Host": "localhost:8080",
      "User-Agent": "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/538.1 (KHTML, like Gecko) PhantomJS/2.1.1 Safari/538.1"
   },
   "httpVersion": "1.1",
   "method": "GET",
   "url": "/foo/response.php"
}

カスタムヘッダーがない場合、accept言語は上記の出力に示されているようになります。 customheaderプロパティを使用して、必要なhttpヘッダーを変更できます。