Экспертная система Delphi.int.ru

Сообщество программистов
Общение, помощь, обмен опытом

Логин:
Пароль:
Регистрация | Забыли пароль?

Delphi.int.ru Expert

Другие разделы портала

Переход к вопросу:

#   

Статистика за сегодня:  


Лучшие эксперты

Подробнее »



Вопрос # 1 721

/ вопрос открыт /

Приветствую, уважаемые эксперты!
Подскажите как сделать Get/Post запрос на URL-адрес и получить ответ. спасибо

HotMan Вопрос ожидает решения (принимаются ответы, доступен мини-форум)

Вопрос задал: HotMan (статус: Посетитель)
Вопрос отправлен: 23 июня 2008, 20:52
Состояние вопроса: открыт, ответов: 2.

Ответ #1. Отвечает эксперт: Вадим К

Здравствуйте, HotMan!
И почему не почитать старые вопросы в этой теме, там точно есть ответы на этот вопрос. всё ведь предельно просто, если например юзать Indy компонент.
Get запрос
s:= idHTTP.Get('http://www.delphi.int.ru'); - и в строковой переменной у вас хтмл текст страницы
Post запрос
sl:TStringList;
sl := TStringList.create;
sl.add('param1=value1');
sl.add('param2=value2');
s := idHTTP1.post('http://ввв.сайт.нет',sl);
sl.free;

вот только проблема есть, если хочеться использовать ssl. Тут инди немного не дружит. Но для этого подпишитесь на рассылку от сайта - в ближайшей будет моя статья об использовании компонентов Synapse для этой цели.
Также неплохо будет почитать уже и други мои статьи на этом сайте
Скачиваем файлы из интернета
Читаем цитаты с bash.org.ru своей программой

Ответ отправил: Вадим К (статус: Академик)
Время отправки: 24 июня 2008, 09:59
Оценка за ответ: 4

Ответ #2. Отвечает эксперт: Feniks

Здравствуйте, HotMan!
Держите в Приложении примеры :
1. Пример HTTP Get - загружаем файлы и страницы из Интернета.
2. Как заполнить форму и отправить на сервер.

Желаю удачи.

Приложение:
  1.  
  2. {*************************************************************}
  3. { HTTPGet component for Delphi 32 }
  4. { Version: 1.94 }
  5. { E-Mail: info@utilmind.com }
  6. { WWW: http://www.utilmind.com }
  7. { Created: October 19, 1999 }
  8. { Modified: June 6, 2000 }
  9. { Legal: Copyright (c) 1999-2000, UtilMind Solutions }
  10. {*************************************************************}
  11. { PROPERTIES: }
  12. { Agent: String - User Agent }
  13. { }
  14. {* BinaryData: Boolean - This setting specifies which type }
  15. {* of data will taken from the web. }
  16. {* If you set this property TRUE then }
  17. {* component will determinee the size }
  18. {* of files *before* getting them from }
  19. {* the web. }
  20. {* If this property is FALSE then as we}
  21. {* do not knows the file size the }
  22. {* OnProgress event will doesn't work. }
  23. {* Also please remember that is you set}
  24. {* this property as TRUE you will not }
  25. {* capable to get from the web ASCII }
  26. {* data and ofter got OnError event. }
  27. { }
  28. { FileName: String - Path to local file to store the data }
  29. { taken from the web }
  30. { Password, UserName - set this properties if you trying to }
  31. { get data from password protected }
  32. { directories. }
  33. { Referer: String - Additional data about referer document }
  34. { URL: String - The url to file or document }
  35. { UseCache: Boolean - Get file from the Internet Explorer's }
  36. { cache if requested file is cached. }
  37. {*************************************************************}
  38. { METHODS: }
  39. { GetFile - Get the file from the web specified in the URL }
  40. { property and store it to the file specified in }
  41. { the FileName property }
  42. { GetString - Get the data from web and return it as usual }
  43. { String. You can receive this string hooking }
  44. { the OnDoneString event. }
  45. { Abort - Stop the current session }
  46. {*************************************************************}
  47. { EVENTS: }
  48. { OnDoneFile - Occurs when the file is downloaded }
  49. { OnDoneString - Occurs when the string is received }
  50. { OnError - Occurs when error happend }
  51. { OnProgress - Occurs at the receiving of the BINARY DATA }
  52. {*************************************************************}
  53.  
  54. unit HTTPGet;
  55.  
  56. interface
  57.  
  58. uses
  59. Windows, Messages, SysUtils, Classes, WinInet;
  60.  
  61. type
  62. TOnProgressEvent = procedure(Sender: TObject; TotalSize, Readed: Integer) of object;
  63. TOnDoneFileEvent = procedure(Sender: TObject; FileName: String; FileSize: Integer) of object;
  64. TOnDoneStringEvent = procedure(Sender: TObject; Result: String) of object;
  65.  
  66. THTTPGetThread = class(TThread)
  67. private
  68. FTAcceptTypes,
  69. FTAgent,
  70. FTURL,
  71. FTFileName,
  72. FTStringResult,
  73. FTUserName,
  74. FTPassword,
  75. FTPostQuery,
  76. FTReferer: String;
  77. FTBinaryData,
  78. FTUseCache: Boolean;
  79.  
  80. FTResult: Boolean;
  81. FTFileSize: Integer;
  82. FTToFile: Boolean;
  83.  
  84. BytesToRead, BytesReaded: DWord;
  85.  
  86. FTProgress: TOnProgressEvent;
  87.  
  88. procedure UpdateProgress;
  89. protected
  90. procedure Execute; override;
  91. public
  92. constructor Create(aAcceptTypes, aAgent, aURL, aFileName, aUserName, aPassword,
  93. aPostQuery, aReferer: String; aBinaryData, aUseCache:
  94. Boolean; aProgress: TOnProgressEvent; aToFile: Boolean);
  95. end;
  96.  
  97. THTTPGet = class(TComponent)
  98. private
  99. FAcceptTypes: String;
  100. FAgent: String;
  101. FBinaryData: Boolean;
  102. FURL: String;
  103. FUseCache: Boolean;
  104. FFileName: String;
  105. FUserName: String;
  106. FPassword: String;
  107. FPostQuery: String;
  108. FReferer: String;
  109. FWaitThread: Boolean;
  110.  
  111. FThread: THTTPGetThread;
  112. FError: TNotifyEvent;
  113. FResult: Boolean;
  114.  
  115. FProgress: TOnProgressEvent;
  116. FDoneFile: TOnDoneFileEvent;
  117. FDoneString: TOnDoneStringEvent;
  118.  
  119. procedure ThreadDone(Sender: TObject);
  120. public
  121. constructor Create(aOwner: TComponent); override;
  122. destructor Destroy; override;
  123.  
  124. procedure GetFile;
  125. procedure GetString;
  126. procedure Abort;
  127. published
  128. property AcceptTypes: String read FAcceptTypes write FAcceptTypes;
  129. property Agent: String read FAgent write FAgent;
  130. property BinaryData: Boolean read FBinaryData write FBinaryData;
  131. property URL: String read FURL write FURL;
  132. property UseCache: Boolean read FUseCache write FUseCache;
  133. property FileName: String read FFileName write FFileName;
  134. property UserName: String read FUserName write FUserName;
  135. property Password: String read FPassword write FPassword;
  136. property PostQuery: String read FPostQuery write FPostQuery;
  137. property Referer: String read FReferer write FReferer;
  138. property WaitThread: Boolean read FWaitThread write FWaitThread;
  139.  
  140. property OnProgress: TOnProgressEvent read FProgress write FProgress;
  141. property OnDoneFile: TOnDoneFileEvent read FDoneFile write FDoneFile;
  142. property OnDoneString: TOnDoneStringEvent read FDoneString write FDoneString;
  143. property OnError: TNotifyEvent read FError write FError;
  144. end;
  145.  
  146. procedure Register;
  147.  
  148. implementation
  149.  
  150. // THTTPGetThread
  151.  
  152. constructor THTTPGetThread.Create(aAcceptTypes, aAgent, aURL, aFileName, aUserName,
  153. aPassword, aPostQuery, aReferer: String; aBinaryData, aUseCache:
  154. Boolean; aProgress: TOnProgressEvent; aToFile: Boolean);
  155. begin
  156. FreeOnTerminate := True;
  157. inherited Create(True);
  158.  
  159. FTAcceptTypes := aAcceptTypes;
  160. FTAgent := aAgent;
  161. FTURL := aURL;
  162. FTFileName := aFileName;
  163. FTUserName := aUserName;
  164. FTPassword := aPassword;
  165. FTPostQuery := aPostQuery;
  166. FTReferer := aReferer;
  167. FTProgress := aProgress;
  168. FTBinaryData := aBinaryData;
  169. FTUseCache := aUseCache;
  170.  
  171. FTToFile := aToFile;
  172. Resume;
  173. end;
  174.  
  175. procedure THTTPGetThread.UpdateProgress;
  176. begin
  177. FTProgress(Self, FTFileSize, BytesReaded);
  178. end;
  179.  
  180. procedure THTTPGetThread.Execute;
  181. var
  182. hSession, hConnect, hRequest: hInternet;
  183. HostName, FileName: String;
  184. f: File;
  185. Buf: Pointer;
  186. dwBufLen, dwIndex: DWord;
  187. Data: Array[0..$400] of Char;
  188. TempStr: String;
  189. RequestMethod: PChar;
  190. InternetFlag: DWord;
  191. AcceptType: LPStr;
  192.  
  193. procedure ParseURL(URL: String; var HostName, FileName: String);
  194.  
  195. procedure ReplaceChar(c1, c2: Char; var St: String);
  196. var
  197. p: Integer;
  198. begin
  199. while True do
  200. begin
  201. p := Pos(c1, St);
  202. if p = 0 then Break
  203. else St[p] := c2;
  204. end;
  205. end;
  206.  
  207. var
  208. i: Integer;
  209. begin
  210. if Pos('http://', LowerCase(URL)) <> 0 then
  211. System.Delete(URL, 1, 7);
  212.  
  213. i := Pos('/', URL);
  214. HostName := Copy(URL, 1, i);
  215. FileName := Copy(URL, i, Length(URL) - i + 1);
  216.  
  217. if (Length(HostName) > 0) and (HostName[Length(HostName)] = '/') then
  218. SetLength(HostName, Length(HostName) - 1);
  219. end;
  220.  
  221. procedure CloseHandles;
  222. begin
  223. InternetCloseHandle(hRequest);
  224. InternetCloseHandle(hConnect);
  225. InternetCloseHandle(hSession);
  226. end;
  227.  
  228. begin
  229. try
  230. ParseURL(FTURL, HostName, FileName);
  231.  
  232. if Terminated then
  233. begin
  234. FTResult := False;
  235. Exit;
  236. end;
  237.  
  238. if FTAgent <> '' then
  239. hSession := InternetOpen(PChar(FTAgent),
  240. INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0)
  241. else
  242. hSession := InternetOpen(nil,
  243. INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
  244.  
  245. hConnect := InternetConnect(hSession, PChar(HostName),
  246. INTERNET_DEFAULT_HTTP_PORT, PChar(FTUserName), PChar(FTPassword), INTERNET_SERVICE_HTTP, 0, 0);
  247.  
  248. if FTPostQuery = '' then RequestMethod := 'GET'
  249. else RequestMethod := 'POST';
  250.  
  251. if FTUseCache then InternetFlag := 0
  252. else InternetFlag := INTERNET_FLAG_RELOAD;
  253.  
  254. AcceptType := PChar('Accept: ' + FTAcceptTypes);
  255. hRequest := HttpOpenRequest(hConnect, RequestMethod, PChar(FileName), 'HTTP/1.0',
  256. PChar(FTReferer), @AcceptType, InternetFlag, 0);
  257.  
  258. if FTPostQuery = '' then
  259. HttpSendRequest(hRequest, nil, 0, nil, 0)
  260. else
  261. HttpSendRequest(hRequest, 'Content-Type: application/x-www-form-urlencoded', 47,
  262. PChar(FTPostQuery), Length(FTPostQuery));
  263.  
  264. if Terminated then
  265. begin
  266. CloseHandles;
  267. FTResult := False;
  268. Exit;
  269. end;
  270.  
  271. dwIndex := 0;
  272. dwBufLen := 1024;
  273. GetMem(Buf, dwBufLen);
  274.  
  275. FTResult := HttpQueryInfo(hRequest, HTTP_QUERY_CONTENT_LENGTH,
  276. Buf, dwBufLen, dwIndex);
  277.  
  278. if Terminated then
  279. begin
  280. FreeMem(Buf);
  281. CloseHandles;
  282. FTResult := False;
  283. Exit;
  284. end;
  285.  
  286. if FTResult or not FTBinaryData then
  287. begin
  288. if FTResult then
  289. FTFileSize := StrToInt(StrPas(Buf));
  290.  
  291. BytesReaded := 0;
  292.  
  293. if FTToFile then
  294. begin
  295. AssignFile(f, FTFileName);
  296. Rewrite(f, 1);
  297. end
  298. else FTStringResult := '';
  299.  
  300. while True do
  301. begin
  302. if Terminated then
  303. begin
  304. if FTToFile then CloseFile(f);
  305. FreeMem(Buf);
  306. CloseHandles;
  307.  
  308. FTResult := False;
  309. Exit;
  310. end;
  311.  
  312. if not InternetReadFile(hRequest, @Data, SizeOf(Data), BytesToRead) then Break
  313. else
  314. if BytesToRead = 0 then Break
  315. else
  316. begin
  317. if FTToFile then
  318. BlockWrite(f, Data, BytesToRead)
  319. else
  320. begin
  321. TempStr := Data;
  322. SetLength(TempStr, BytesToRead);
  323. FTStringResult := FTStringResult + TempStr;
  324. end;
  325.  
  326. inc(BytesReaded, BytesToRead);
  327. if Assigned(FTProgress) then
  328. Synchronize(UpdateProgress);
  329. end;
  330. end;
  331.  
  332. if FTToFile then
  333. FTResult := FTFileSize = Integer(BytesReaded)
  334. else
  335. begin
  336. SetLength(FTStringResult, BytesReaded);
  337. FTResult := BytesReaded <> 0;
  338. end;
  339.  
  340. if FTToFile then CloseFile(f);
  341. end;
  342.  
  343. FreeMem(Buf);
  344.  
  345. CloseHandles;
  346. except
  347. end;
  348. end;
  349.  
  350. // HTTPGet
  351.  
  352. constructor THTTPGet.Create(aOwner: TComponent);
  353. begin
  354. inherited Create(aOwner);
  355. FAcceptTypes := '*/*';
  356. FAgent := 'UtilMind HTTPGet';
  357. end;
  358.  
  359. destructor THTTPGet.Destroy;
  360. begin
  361. Abort;
  362. inherited Destroy;
  363. end;
  364.  
  365. procedure THTTPGet.GetFile;
  366. var
  367. Msg: TMsg;
  368. begin
  369. if not Assigned(FThread) then
  370. begin
  371. FThread := THTTPGetThread.Create(FAcceptTypes, FAgent, FURL, FFileName, FUserName,
  372. FPassword, FPostQuery, FReferer, FBinaryData, FUseCache, FProgress, True);
  373. FThread.OnTerminate := ThreadDone;
  374. if FWaitThread then
  375. while Assigned(FThread) do
  376. while PeekMessage(Msg, 0, 0, 0, PM_REMOVE) do
  377. begin
  378. TranslateMessage(Msg);
  379. DispatchMessage(Msg);
  380. end;
  381. end
  382. end;
  383.  
  384. procedure THTTPGet.GetString;
  385. var
  386. Msg: TMsg;
  387. begin
  388. if not Assigned(FThread) then
  389. begin
  390. FThread := THTTPGetThread.Create(FAcceptTypes, FAgent, FURL, FFileName, FUserName,
  391. FPassword, FPostQuery, FReferer, FBinaryData, FUseCache, FProgress, False);
  392. FThread.OnTerminate := ThreadDone;
  393. if FWaitThread then
  394. while PeekMessage(Msg, 0, 0, 0, PM_REMOVE) do
  395. begin
  396. TranslateMessage(Msg);
  397. DispatchMessage(Msg);
  398. end;
  399. end
  400. end;
  401.  
  402. procedure THTTPGet.Abort;
  403. begin
  404. if Assigned(FThread) then
  405. begin
  406. FThread.Terminate;
  407. FThread.FTResult := False;
  408. end;
  409. end;
  410.  
  411. procedure THTTPGet.ThreadDone(Sender: TObject);
  412. begin
  413. FResult := FThread.FTResult;
  414. if FResult then
  415. if FThread.FTToFile then
  416. if Assigned(FDoneFile) then FDoneFile(Self, FThread.FTFileName, FThread.FTFileSize) else
  417. else
  418. if Assigned(FDoneString) then FDoneString(Self, FThread.FTStringResult) else
  419. else
  420. if Assigned(FError) then FError(Self);
  421. FThread := nil;
  422. end;
  423.  
  424. procedure Register;
  425. begin
  426. RegisterComponents('UtilMind', [THTTPGet]);
  427. end;
  428.  
  429. end.
  430.  
  431.  
  432.  
  433.  
  434.  
  435.  
  436. <form method=GET action=http://localhost/cgi-bin/mget?>
  437.  
  438.  
  439. <input type=submit>
  440. </form>
  441.  
  442.  
  443.  
  444.  
  445.  
  446.  
  447.  
  448.  
  449.  
  450.  
  451. var
  452. s: String;
  453. begin
  454. s := IdHTTP1.Get('http://localhost/cgi-bin/mget?name1=Vasya&name2=Pupkin')
  455.  
  456. <form method=POST action=http://localhost/cgi-bin/mget?>
  457.  
  458.  
  459. <input type=submit>
  460. </form>
  461.  
  462. var
  463. tL: TStringList;
  464. s: String;
  465. begin
  466. tL := TStringList.Create;
  467. tL.Add('name1=Vasya');
  468. tL.Add('name2=Pupkin');
  469. try
  470. s := IdHTTP1.Post('http://localhost/cgi-bin/mget',tL);
  471. finally
  472. tL.Free;
  473. end;


Ответ отправил: Feniks (статус: Бакалавр)
Время отправки: 24 июня 2008, 10:06
Оценка за ответ: 5


Мини-форум вопроса

Мини-форум пуст.

Чтобы оставлять сообщения в мини-форумах, Вы должны авторизироваться на сайте.

Версия движка: 2.6+ (26.01.2011)
Текущее время: 22 февраля 2025, 11:46
Выполнено за 0.02 сек.