2011-02-06 24 views
1

嘿,我想用java程序填充html表單,但我卡住了一半。實際上我能夠獲取頁面,但不能將其寫回服務器,或者可能能夠將其寫回,但沒有來自服務器的響應。使用java中的套接字填充html表格

這是我的計劃:

import java.net.*; 
import java.io.*; 

public class fillForm{ 
    public static void main(String args[]){ 
     Socket s = null; 
     try{ 
      s = new Socket("localhost", 80); 
      BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); 
      BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); 
      /****************** 
       Now download the page from the server. 
      ******************/ 
      bw.write("GET /phpsandbox/form.html HTTP/1.1\n"); 
      bw.write("Host: localhost:80\n\n"); 
      bw.flush(); 
      readResponse(br); 
      //now i have read whole input now its time to write output. 
      bw.write("GET /phpsandbox/form.php?uName=hello HTTP/1.1\n"); 
      bw.write("Host: localhost:80\n\n"); 
      bw.flush(); 
      readResponse(br); 
     }catch(IOException e){ 
      System.out.println("IO: " + e.getMessage()); 
     }catch(Exception e){ 
      System.out.println("Exception: " + e.getMessage()); 
     }     
    } 
    public static void readResponse(BufferedReader br){ 
     String newLine; 
     try{ 
      while((newLine = br.readLine())!=null){ 
       System.out.println("Line: " + newLine); 
      } 
     }catch(IOException e){ 
      System.out.println("IO: " + e.getMessage()); 
     } 
    } 
} 

ND這裏是form.html

<html> 
<head><title>form</title></head> 
<body> 
<form action="form.php" method="GET"> 
<label>Enter name</label> 
<input name="uName"/> 
<input type="submit" /> 
</form> 
</body> 
</html> 

,這裏是form.php的駐留在同一文件夾中form.html

<?php 
     //read the response from the client 
     echo "hELLO"; 
     echo $_GET['uName']; 
?> 

這裏是輸出:

Line: HTTP/1.1 200 OK 
Line: Date: Sun, 06 Feb 2011 13:46:17 GMT 
Line: Server: Apache/2.2.11 (Unix) DAV/2 mod_ssl/2.2.11 OpenSSL/0.9.8k PHP/5.2.9 mod_apreq2-20051231/2.6.0 mod_perl/2.0.4 Perl/v5.10.0 
Line: Last-Modified: Sun, 06 Feb 2011 13:29:58 GMT 
Line: ETag: "6c3c-b5-49b9d1c8f56c1" 
Line: Accept-Ranges: bytes 
Line: Content-Length: 181 
Line: Content-Type: text/html 
Line: 
Line: <html> 
Line: <head><title>form</title></head> 
Line: <body> 
Line: <form action="form.php" method="GET"> 
Line: <label>Enter name</label> 
Line: <input name="uName"/> 
Line: <input type="submit" /> 
Line: </form> 
Line: </body> 
Line: </html> 

給出輸出程序等待一段時間後退出。

謝謝:)

+0

你爲什麼這樣做?你爲什麼不寫簡單的HTTP servlet? – AlexR 2011-02-06 15:10:26

+1

您是否考慮過使用更合適的庫,例如Apache HTTPComponents? http://hc.apache.org/ – 2011-02-06 16:38:14

回答