我正在尝试从雅虎搜索中获取结果并将这些结果保存到文件中。但是,当我使用IdHTTP时会出现异常。它显示“Exception,Socket Error#10014 Bad address。”。下面是我的代码:
function TfrmIdHTTP.GetYahooSearch(const aSearch: String;
var aResponse: String): Boolean;
var
mHost, mPath, mQuery : String;
mResult, mStrBlock : String;
mQueryStream : TStringStream;
mResultStream : TStringStream;
begin
Result := False;
Try
pbStatus.Position := 10;
mHost := 'http://www.yahoo.com';
mPath := '/';
mQueryStream := TStringStream.Create('');
mResultStream := TStringStream.Create('');
IdHTTP.HandleRedirects := True;
IdHTTP.Request.ContentType := 'application/x-www-form-urlencoded';
pbStatus.Position := 30;
IdHTTP.Get(mHost + mPath, mResultStream);
showmessage('1');
mResult := mResultStream.DataString;
SaveFile('yahoo_search_01.htm', mResult, True);
pbStatus.Position := 50;
mStrBlock := StringCrop(mResult, '<form', '</form>',1);
if PosEx('role="search"', mStrBlock) = 0 then
begin
aResponse := 'Error, please check and try again later';
Exit;
end;
pbStatus.Position := 70;
mHost := 'http://www.yahoo.com';
mPath := '/search';
mQuery := 'toggle=' + Utf8ToAnsi(StringCrop(mStrBlock, 'name="toggle" value="', '">', 1))
+ '&cop=' + Utf8ToAnsi(StringCrop(mStrBlock, 'name="cop" value="', '">', 1))
+ '&ei=' + Utf8ToAnsi(StringCrop(mStrBlock, 'name="ei" value="', '">', 1))
+ '&.tsrc=' + Utf8ToAnsi(StringCrop(mStrBlock, 'name=".tsrc" value="', '">', 1))
+ '&p=' + Utf8ToAnsi(Trim(edtSearch.Text))
;
mQueryStream.WriteString(mQuery);
pbStatus.Position := 90;
IdHTTP.Post(mHost + mPath, mQueryStream, mResultStream);
mResult := mResultStream.DataString;
SaveFile('yahoo_search_02.htm', mResult, True);
Except
on E:Exception do begin
aResponse := Format('%s, %s', ['Exception', e.Message]);
Exit;
end;
end;
aResponse := mResult;
Result := True;
end;