用Delphi的TIdHttp控制項發起POST請求和Java的Servlet響應

來源:互聯網
上載者:User

使用Delphi的TIdHttp控制項發起一個POST請求很簡單,定義一個TStringList執行個體,往上面添加參數就行:

procedure TForm1.Button1Click(Sender: TObject);
var
  HttpClient: TIdHttp;
  ParamList: TStringList;
begin
  HttpClient := TIdHttp.Create();
  ParamList := TStringList.Create;
  ParamList.Add('user=pan');
  ShowMessage(HttpClient.Post('http://192.168.0.105:8080/Servlets/Submit', ParamList));
end;

運行代碼,使用WireShark抓包工具看到這個POST請求發出來了,Content-Type是application/x-www-form-urlencoded,這種類型的意思是將參數打包成key-value的形式。



然後來看看服務端的Java代碼:

public class Submit extends HttpServlet {

  ...

  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    response.getWriter().println("Hello Servlet, " + request.getParameter("user") + "!");

  }

}

用戶端收到Post的響應,就會把“Hello Servlet, pan!”這段文字顯示出來了。


補充:

當post的參數值帶中文時,會被編碼為UTF8格式,例如POST方法的WIRESHARK抓包:


再看200 OK訊息的抓包:



此時不能直接使用TIdHTTP.Post方法返回的字串,而是要對其正確解碼,否則讀到的是亂碼:

procedure TForm1.Button1Click(Sender: TObject);var  HttpClient: TIdHttp;  ParamList: TStringList;  SS: TStringStream;begin  SS := TStringStream.Create('', TEncoding.UTF8);  HttpClient := TIdHttp.Create();  ParamList := TStringList.Create;  ParamList.Add('action=測 試');  ParamList.Add('user=用 戶');  HttpClient.Post('http://192.168.0.102:8080/HelloServlet/Submit', ParamList, SS);  ShowMessage(SS.DataString);end;
解決亂碼問題的方法在於我們通過TStringStream將返回的字元流按UTF8解碼。


 補充2:當POST方法中有兩個相同的參數名時,例如:

procedure TForm1.Button1Click(Sender: TObject);var  HttpClient: TIdHttp;  ParamList: TStringList;  SS: TStringStream;begin  SS := TStringStream.Create('', TEncoding.UTF8);  HttpClient := TIdHttp.Create();  ParamList := TStringList.Create;  ParamList.Add('action=測 試');  ParamList.Add('user=用 戶1');  ParamList.Add('user=用 戶2');  HttpClient.Post('http://192.168.0.100:8080/HelloServlet/Submit', ParamList, SS);  ShowMessage(SS.DataString);end;

此時在伺服器端如果仍然使用getParameter方法,則只能返回第一個值“用 戶1”,需要使用getParameterValues方法:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stub//response.getWriter().println("Hello Servlet, " + request.getParameter("user") + "!");String[] user = request.getParameterValues("user"); response.getWriter().println("Hello Servlet, " + user[0] + " and " + user[1] + "!");}

此時用戶端收到:



因此同名參數的兩個值都讀出來了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.