WebRequest
WebRequest
发送 HTTP 请求到指定服务器。 该函数有两个版本:
- 发送简单请求 使用内容-类型标题的"key=value"类型:application/x-www-form-urlencoded
int WebRequest(
const string method, // HTTP 请求方式
const string url, // url 地址
const string cookie, // cookie
const string referer, // 参照页
int timeout, // 超时
const char &data[], // HTTP请求信息数组
int data_size, // data[] 数组大小
char &result[], // 服务器响应数据数组
string &result_headers // 服务器响应标头
);- 发送任何类型的请求 为了各种网络服务的更灵活互动指定自定义的标题设置。
int WebRequest(
const string method, // HTTP 方法
const string url, // URL
const string headers, // 标题
int timeout, // 超时
const char &data[], // HTTP 信息主体的数组
char &result[], // 包含服务器反应数据的数组
string &result_headers // 服务器响应标题
);参数
- method
[in] HTTP 请求方法。
- url
[in] URL 地址。
- headers
[in] “key: value"类型的请求标题,以分行符 “\r\n"分隔。
- cookie
[in] Cookie。
- referer
[in] HTTP 请求标头的推荐页字段
- timeout
[in] 超时时间以毫秒为单位。
- data[]
[in] HTTP 请求信息数组。
- data_size
[in] data[] 数组大小。
- result[]
[out] 服务器响应数据数组。
- result_headers
[out] 服务器响应标头。
返回值
服务器响应的HTTP 状态码,或错误情况下的 -1 。
注意
若要能够使用WebRequest 函数,您必须在“选项”窗口“EA交易”标签的允许URLs列表中添加一个URL。
WebRequest 是一个同步函数。这意味着它会阻止程序执行并且等候请求服务器的响应。当收到发送请求的响应时,延迟至关重要,这就是禁止从指标调用该函数的原因,因为指标按照交易品种组指标的自己的执行线程操作。在一个图表上执行指标延迟可能导致该交易品种的所有图表停止更新。
该函数只能从专家和脚本调用,因为他们按照自己的执行线程操作。从指标调用,GetLastError() 函数将返回错误4014 “函数不允许调用”。
WebRequest() 函数不能在 策略测试中执行。
例如:
void OnStart()
{
string cookie=NULL,headers;
char post[],result[];
string url="https://finance.yahoo.com";
//--- To enable access to the server, you should add URL "https://finance.yahoo.com"
//--- to the list of allowed URLs (Main Menu->Tools->Options, tab "Expert Advisors"):
//--- Resetting the last error code
ResetLastError();
//--- Downloading a html page from Yahoo Finance
int res=WebRequest("GET",url,cookie,NULL,500,post,0,result,headers);
if(res==-1)
{
Print("Error in WebRequest. Error code =",GetLastError());
//--- Perhaps the URL is not listed, display a message about the necessity to add the address
MessageBox("Add the address '"+url+"' to the list of allowed URLs on tab 'Expert Advisors'","Error",MB_ICONINFORMATION);
}
else
{
if(res==200)
{
//--- Successful download
PrintFormat("The file has been successfully downloaded, File size %d byte.",ArraySize(result));
//PrintFormat("Server headers: %s",headers);
//--- Saving the data to a file
int filehandle=FileOpen("url.htm",FILE_WRITE|FILE_BIN);
if(filehandle!=INVALID_HANDLE)
{
//--- Saving the contents of the result[] array to a file
FileWriteArray(filehandle,result,0,ArraySize(result));
//--- Closing the file
FileClose(filehandle);
}
else
Print("Error in FileOpen. Error code =",GetLastError());
}
else
PrintFormat("Downloading '%s' failed, error code %d",url,res);
}
}