В принципе, я уже делал такой пост
Как отправить файл с помощью idHTTP и принять его на idHTTPServer ?
Но в данном случае хочу акцентировать внимание именно на отправке и приеме параметров методом POST.
Как это будет выглядеть?
Как отправить POST запрос с параметрами при помощи idHTTP?
1 2 |
uses IdMultipartFormData |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
procedure TVisualFrame_HTTP.SendPOSTParamsClick(Sender: TObject); var PostData: TIdMultiPartFormDataStream; FileName:string; Error:string; ResponseText:string; begin if not IsHTTPConnectionOk(Error,ResponseText) then Exit; PostData := TIdMultiPartFormDataStream.Create; try idHTTP.Request.Referer := HTTPServerToRequest+'/SomeURICommand'; idHTTP.Request.ContentType := 'multipart/form-data'; PostData.AddFormField('SomePOSTParam1','SomePostParamValue1'); PostData.AddFormField('SomePOSTParam2','SomePostParamValue2'); // PostData.AddFile('attach', FileName, 'application/x-rar-compressed'); // PostData.AddFormField('field2', 'msg2'); // PostData.AddFormField('action', 'post'); idHTTP.Post(HTTPServerToRequest+'/SomeURICommand', PostData); Application.ProcessMessages; finally if(Assigned(PostData)) then PostData.Free; ShowMessage('idHTTP Sent OK'); end; end; |
Как принять этот запрос на сервере и декодировать?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
procedure TfHTTPServer.IdHTTPServerCommandGet (AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); var DecodePostRequest:TDecodePostRequest; PostParams:TStringList; begin PostParams:=TStringList.Create; if ARequestInfo.URI=('/SomeURICommand') then begin PostParams.Clear; DecodePostRequest:=TDecodePostRequest.Create(Self); DecodePostRequest.Decode(AContext,ARequestInfo,AResponseInfo,PostParams); FreeAndNil(DecodePostRequest); ShowMessage( 'SomePOSTParam1='+ PostParams.Values['SomePOSTParam1'] // Example how to check one of the params... ); end; FreeAndNil(PostParams); end; |
Само декодирование я вынес в отдельный юнит
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 |
unit uDecodePOstRequest; interface uses System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IdBaseComponent, IdComponent, IdCustomTCPServer, IdCustomHTTPServer, IdHTTPServer, Vcl.StdCtrls, HTTPApp, IdMultipartFormData, IdContext ; type TQuery = record params: TStringList; values: TStringList; end; type TDecodePostRequest = class(TDataModule) private Params:TStringList; Query: TQuery; function ReadMultipartRequest(const Boundary: Ansistring; ARequest: Ansistring; var AHeader: TStringList; var Data: Ansistring): Ansistring; procedure QueryParsing(list: TStrings; var params, values: TStringList); procedure QueryPreParsing(s: string; var res: TStringList); { Private declarations } public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Decode(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo; var PostParams:TStringList); end; //var // ReceiveOneFileDM: TReceiveOneFile; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} uses uHTTPServer_Main; var HTTPServer_Main_UnitVar:TfHTTPServer; procedure TDecodePostRequest.Decode(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo; var PostParams:TStringList); const MaxReadBlockSize = 8192; UploadPath = ''; var MemoryStream: TMemoryStream; Boundary, BufferStr, AllContent: Ansistring; Header: TStringList; ByteToRead, ReadedBytes, RSize: Integer; Buffer: PAnsiChar; Data: Ansistring; HList: TStrings; OutStream: TFileStream; begin AResponseInfo.Server := 'ver1'; AResponseInfo.CacheControl := 'no-cache'; if(ARequestInfo.Host = 'localhost:40000') then begin // if(ARequestInfo.Document = '/index.php') then begin if (Pos('multipart/form-data', LowerCase(ARequestInfo.ContentType))>0) and // далее идёт обработка multipart (Pos('boundary', LowerCase(ARequestInfo.ContentType))>0) then begin Header := TStringList.Create; try ExtractHeaderFields([';'], [' '], PChar(ARequestInfo.ContentType), Header, False, False); Boundary := Header.Values['boundary']; finally Header.Free; end; MemoryStream := TMemoryStream.Create; try MemoryStream.LoadFromStream(ARequestInfo.PostStream); AllContent := ''; ByteToRead := ARequestInfo.ContentLength; try while ByteToRead > 0 do begin RSize := MaxReadBlockSize; if RSize > ByteToRead then RSize := ByteToRead; GetMem(Buffer, RSize); try ReadedBytes := MemoryStream.Read(Buffer^, RSize); SetString(BufferStr, Buffer, ReadedBytes); AllContent := AllContent + BufferStr; finally FreeMem(Buffer, RSize); end; ByteToRead := ARequestInfo.ContentLength - Length(AllContent); end; AResponseInfo.ContentText := 'ok'; AResponseInfo.WriteContent; except on E: Exception do begin AResponseInfo.ContentText := E.Message; AResponseInfo.WriteContent; end; end; finally MemoryStream.Free; end; if ARequestInfo.ContentLength = Length(AllContent) then while Length(AllContent) > Length('--' + Boundary + '--' + #13#10) do begin Header := TStringList.Create; HList := TStringList.Create; try AllContent := ReadMultipartRequest('--' + Boundary, AllContent, Header, Data); ExtractHeaderFields([';'], [' '], PChar(Header.Values['Content-Disposition']), HList, False, True); if (Header.Values['Content-Type'] <> '') and (Data <> '') and(HList.Values['filename']<>'') // << corrected here then begin OutStream:=TFileStream.Create(UploadPath + ExtractFileName(HList.Values['filename']), fmCreate); try try OutStream.WriteBuffer(Pointer(Data)^, Length(Data)); HTTPServer_Main_UnitVar.mmo3.Lines.Add('File Successfully Uploaded'); except on E:Exception do ShowMessage(E.ClassName+' Exception Raised : ' +#13#10+#13#10+E.Message); end; finally OutStream.Free; end end else begin HTTPServer_Main_UnitVar.mmo3. Lines.Add(Format('<p>Field <b>%s</b> = %s',[HList.Values['name'], Data])); // Collecting Post Params in External Var PostParams.Add(HList.Values['name']+'='+Data); // PS Gathering Params Here end; finally HTTPServer_Main_UnitVar.mmo1.Lines := Header; HTTPServer_Main_UnitVar.mmo2.Lines := HList; Header.Free; HList.Free; end; end; end; if(Pos('application/x-www-form-urlencoded', LowerCase(ARequestInfo.ContentType))>0) then begin MemoryStream := TMemoryStream.Create; try MemoryStream.LoadFromStream(ARequestInfo.PostStream); AllContent := ''; ByteToRead := ARequestInfo.ContentLength; try while ByteToRead > 0 do begin RSize := MaxReadBlockSize; if RSize > ByteToRead then RSize := ByteToRead; GetMem(Buffer, RSize); try ReadedBytes := MemoryStream.Read(Buffer^, RSize); SetString(BufferStr, Buffer, ReadedBytes); AllContent := AllContent + BufferStr; finally FreeMem(Buffer, RSize); end; ByteToRead := ARequestInfo.ContentLength - Length(AllContent); end; AResponseInfo.ContentText := 'ok'; AResponseInfo.WriteContent; except on E: Exception do begin AResponseInfo.ContentText := E.Message; AResponseInfo.WriteContent; end; end; finally MemoryStream.Free; end; QueryPreParsing(AllContent, Params); QueryParsing(Params, Query.params, Query.values); HTTPServer_Main_UnitVar.mmo1.Lines := Query.params; HTTPServer_Main_UnitVar.mmo2.Lines := Query.values; end; end; end; end; function TDecodePostRequest.ReadMultipartRequest(const Boundary: Ansistring; ARequest: Ansistring; var AHeader: TStringList; var Data: Ansistring): Ansistring; var Req, RHead: string; i: Integer; begin Result := ''; AHeader.Clear; Data := ''; if (Pos(Boundary, ARequest) < Pos (Boundary + '--', ARequest)) and (Pos(Boundary, ARequest) = 1) then begin Delete(ARequest, 1, Length(Boundary) + 2); Req := Copy(ARequest, 1, Pos(Boundary, ARequest) - 3); Delete(ARequest, 1, Length(Req) + 2); RHead := Copy(Req, 1, Pos(#13#10#13#10, Req)-1); Delete(Req, 1, Length(RHead) + 4); AHeader.Text := RHead; for i := 0 to AHeader.Count - 1 do if Pos(':', AHeader.Strings[i]) > 0 then AHeader.Strings[i] := Trim(Copy(AHeader.Strings[i], 1, Pos(':', AHeader.Strings[i])-1)) + '=' + Trim(Copy(AHeader.Strings[i], Pos(':', AHeader.Strings[i])+1, Length(AHeader.Strings[i]) - Pos(':', AHeader.Strings[i]))); Data := Req; Result := ARequest; end end; //-------------------------Some Additional methods procedure TDecodePostRequest.QueryPreParsing(s: string; var res: TStringList); var ss: string; p: integer; begin if(Pos('=',s) <= 0) then begin Exit; end; end; constructor TDecodePostRequest.Create(AOwner: TComponent); begin inherited; if (AOwner is TfHTTPServer) then HTTPServer_Main_UnitVar:=(AOwner as TfHTTPServer); Query.params := TStringList.Create; Query.values := TStringList.Create; Params:=TStringList.Create; end; destructor TDecodePostRequest.Destroy; begin inherited; FreeAndNil(Query.params); FreeAndNil(Query.values); FreeAndNil(Params); end; procedure TDecodePostRequest.QueryParsing(list: TStrings; var params: TStringList; var values: TStringList); var i: Integer; p: integer; begin params.Clear; values.Clear; for i := 0 to list.Count-1 do begin p := Pos('=', list.Strings[i]); params.Add(Copy(list.Strings[i], 1, p-1)); values.Add(Copy(list.Strings[i], p+1, Length(list.Strings[i]))); end; end; end. |