在java中使用socket填充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());
}
}
}
这是表格。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>
这是表格。php与表单位于同一文件夹中。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>
给出输出后,程序等待一段时间,然后退出
谢谢:)
# 1 楼答案
了解HTTP协议;看看这里的例子:http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html。我想在第一个GET和第二个GET之间需要几行空白
如果失败了,请关闭插座并打开一个新的,这样应该可以工作