簡體   English   中英

我的帖子tidtcpclient中的錯誤在哪里?

[英]Where is the error in my post tidtcpclient?

我收到一個錯誤的請求,我的代碼有什么問題

procedure TForm1.Button1Click(Sender: TObject);
begin
  TCPClient1.Host :='aavtrain.com';
  TCPClient1.Port := 80;
  TCPClient1.ConnectTimeout := 10000;
  TCPClient1.OnConnected := TCPClient1Connected;
  TCPClient1.ReadTimeout := 5000;
  TCPClient1.Connect;
end;

procedure TForm1.TCPClient1Connected(Sender: TObject);
var
  s: string;
begin
  //
  TCPClient1.Socket.WriteLn('POST HTTP/1.1');
  TCPClient1.Socket.WriteLn(sLineBreak);
  IdTCPClient1.Socket.WriteLn('http://aavtrain.comindex.asp');
  IdTCPClient1.Socket.WriteLn(sLineBreak);
  TCPClient1.Socket.WriteLn('user_name=binary');
  TCPClient1.Socket.WriteLn('&password=12345');
  TCPClient1.Socket.WriteLn('&Submit=Submit');
  TCPClient1.Socket.WriteLn('&login=true');
  TCPClient1.Socket.WriteLn(sLineBreak);
  repeat
    s := TCPClient1.Socket.ReadLn('');
    Memo1.Lines.Add(s);
  until s.Contains('try again');
  TCPClient1.Disconnect;
end;

您的HTTP消息完全格式錯誤,您發送到服務器的每一行都是錯誤的。


HTTP消息由三部分組成-單個請求/響應行,緊隨其后的是標題,然后是正文。 標頭和正文由單個CRLF CRLF序列分隔,但是您要在POST請求行之后發送CRLF CRLF CRLF序列。 實際上,您通常發送太多的換行符。

POST行本身缺少所請求資源的路徑。

您根本沒有發送任何HTTP標頭。 您正在請求HTTP 1.1,它需要一個Host標頭。 並且您沒有發送Content-Type標頭,因此服務器知道您要發布的數據類型,或者不是Content-Length標頭,因此服務器知道您要發布多少數據。

郵件正文本身也格式不正確。 您需要將Webform值作為一行發送,而不是作為每個值的單獨行發送。

嘗試以下方法:

procedure TForm1.Button1Click(Sender: TObject);
var
  PostData, Response: string;
  Enc: IIdTextEncoding;
begin
  PostData := 'user_name=binary&password=12345&Submit=Submit&login=true';
  Enc := IndyTextEncoding_UTF8;
  //
  TCPClient1.Host := 'aavtrain.com';
  TCPClient1.Port := 80;
  TCPClient1.ConnectTimeout := 10000;
  TCPClient1.ReadTimeout := 5000;
  TCPClient1.Connect;
  try
    TCPClient1.Socket.WriteLn('POST /index.asp HTTP/1.1');
    TCPClient1.Socket.WriteLn('Host: aavtrain.com');
    TCPClient1.Socket.WriteLn('Content-Type: application/x-www-form-urlencoded; charset=utf-8');
    TCPClient1.Socket.WriteLn('Content-Length: ' + IntToStr(Enc.GetByteCount(PostData)));
    TCPClient1.Socket.WriteLn('Connection: close');
    TCPClient1.Socket.WriteLn;
    TCPClient1.Socket.Write(PostData, Enc);

    // the following is NOT the right way to read
    // an HTTP response. This is just an example.
    // I'll leave it as an exercise for you to
    // research and figure out the proper way.
    // I've posted pseudo code for this on
    // StackOverflow many times before...
    Response := TCPClient1.Socket.AllData;
  finally
    TCPClient1.Disconnect;
  end;
  Memo1.Text := Response;
end;

請閱讀RFC 2616和相關的RFC,以及有關HTML Webform提交的W3C規范(請參閱HTML 4.01HTML5 ),因為您顯然不了解HTTP的實際工作原理。 從頭開始實現所有內容並非易事,因為它是一個非常復雜且涉及廣泛的協議。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM