使用java程序获取页面,然后在填写后将其发回

时间:2010-12-22 13:34:36

标签: java networking

我必须这样做,因为我的任务如下: 编写一个java程序从服务器获取一个html页面,然后使用java程序填写表单,然后将其发送回服务器。

为此,我编写了以下代码:

    class htmlPageFetch{
        public static void main(String[] args){
                try{
                        Socket s = new Socket("127.0.0.1", 80);
                        DataInputStream dIn = new DataInputStream(s.getInputStream());


        PrintWriter dOut = new PrintWriter(s.getOutputStream(), true);
                    dOut.println("GET /mytesting/justCheck.html HTTP/1.1\r\nHost:localhost\r\n\r\n");
                    boolean more_data = true;
                    String str;
                    while(more_data){


     str = dIn.readLine();
                                    if(str==null){
                                            //Now server has stopped sending data                                           //So now write again the inputs
//So i had written the following code but not working
    dOut.println("POST /mytesting/save.php HTTP/1.1\r\nHost:localhost\r\n\r\n");
    dOut.println("some=helloworld");
                                            more_data = false;
                                            continue;
                                    }
                                    System.out.println(str);
                            }
                    }catch(IOException e){

                    }
            }
    }

这是html文件:

        <html>
    <head>
    <title>Title goes here</title>
    </head>
    <body>
    <p>Hello world</p>
    <form action="save.php" method="post">
    Enter some thing here <input name="some"/>
    <br/>
    <input type="submit" value="Send"/>
    <input type="reset" value="Cancel"/>
    </form>
    </body>
    </html>

and the save.php just echo back the string entered.

So how to send back the filled form to the server back.

Thanks in Advance.

1 个答案:

答案 0 :(得分:0)

我强烈建议您使用JSoup(http://jsoup.org/)。它基本上是java的jquery。您可以非常轻松地获取输入字段。