HTTP POST与印(Http Post with indy)

2019-06-24 20:03发布

我有我的Web服务器上的一个简单的PHP脚本,我需要上传使用HTTP POST,这是我在德尔福正在做的一个文件。

这是我与印地代码,但aparantely它不会工作,我想不出什么我没有做正确。 如何查看我的服务器上发送的是有这样的工具吗?

procedure TForm1.btn1Click(Sender: TObject);
var
  fname : string;
  MS,dump : TMemoryStream;
  http  : TIdHTTP;

const
  CRLF = #13#10;
begin
  if PromptForFileName(fname,'','','','',false) then
  begin
    MS := TMemoryStream.Create();
    MS.LoadFromFile(fname);
    dump := TMemoryStream.Create();
    http := TIdHTTP.Create();
    http.Request.ContentType:='multipart/form-data;boundary =-----------------------------7cf87224d2020a';
    fname := CRLF + '-----------------------------7cf87224d2020a' + CRLF + 'Content-Disposition: form-data; name=\"uploadedfile\";filename=\"test.png"' + CRLF;
    dump.Write(fname[1],Length(fname));
    dump.Write(MS.Memory^,MS.Size);
    fname := CRLF + '-----------------------------7cf87224d2020a--' + CRLF;
    dump.Write(fname[1],Length(fname));
    ShowMessage(IntToStr(dump.Size));
    MS.Clear;
    try
    http.Request.Method := 'POST';
    http.Post('http://posttestserver.com/post.php',dump,MS);
    ShowMessage(PAnsiChar(MS.Memory));
    ShowMessage(IntToStr(http.ResponseCode));
    except
    ShowMessage('Could not bind socket');
    end;
  end;
end;

Answer 1:

印有TIdMultipartFormDataStream用于此目的:

procedure TForm1.SendPostData;
var
  Stream: TStringStream;
  Params: TIdMultipartFormDataStream;
begin
  Stream := TStringStream.Create('');
  try
   Params := TIdMultipartFormDataStream.Create;
   try
    Params.AddFile('File1', 'C:\test.txt','application/octet-stream');
    try
     HTTP.Post('http://posttestserver.com/post.php', Params, Stream);
    except
     on E: Exception do
       ShowMessage('Error encountered during POST: ' + E.Message);
    end;
    ShowMessage(Stream.DataString);
   finally
    Params.Free;
   end;
  finally
   Stream.Free;
  end;
end;


Answer 2:

从调用一个印PHP可能会失败,因为用户代理的,那么你会得到403错误。

试试这个方式,固定对我来说:

var Answer: string;
begin
  GetHTML:= TIdHTTP.create(Nil);
  try
    GetHTML.Request.UserAgent:= 'Mozilla/3.0';
    Answer:= GetHTML.Get('http://www.testserver.com/test.php?id=1');
  finally
    GetHTML.Free;
  end;
end;


Answer 3:

你失去了2个字符“ - ”。 这是更好地做到这一点:

http.Request.ContentType:='multipart/form-data;boundary='+myBoundery;
fname := CRLF + '--' + myBoundery + CRLF + 'Content-Disposition: form-data; name=\"uploadedfile\";filename=\"test.png"' + CRLF;


文章来源: Http Post with indy