PhantomJS customHeaders 头部设置方法详解


发布日期 : 2024-08-21 04:30:52 UTC

访问量: 10 次浏览

PhantomJS customHeaders 属性

customHeaders 函数指定了会发送到服务器的每个请求的额外的HTTP请求头。默认值是一个空对象”{}”。在发送到服务器之前,头部名称和值会以US-ASCII进行编码。

语法

customHeaders 语法如下:

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

使用自定义标题的输出

上述程序生成了以下输出。

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

在上面的示例中,我们使用自定义头部来设置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"
}

没有自定义的头部信息,接受的语言如上输出所示。使用 customheader 属性,您可以更改所需的http头信息。