whether 数据正确发送 or not depends on the returning html data, you need to parse it yourself to determine what is correct, what is wrong. Here is an complete example which 模拟浏览器使用post方法向表单发送数据 using socket:import java.net.*;
import java.io.*;
import java.util.*;public class TestHTTP {
    static  String home="www.csdn.net";
    static String script = "/member/logon.asp";
    static  String sdata  = "name=xxxx&pass=yyyy&type=1";    static String ctype = "application/x-www-form-urlencoded";    static  int    port=80;    static  String rdata  = "";
    public static void main(String[] args) {
        Socket           sock=null;
        DataOutputStream dataout;
BufferedReader  datain;        try {            System.out.println(ctype);
            //create a client socket
            sock = new Socket(home, port);
            // Obtain output stream to communicate with the server
            dataout = new DataOutputStream(sock.getOutputStream());
    datain =  new BufferedReader(new InputStreamReader(sock.getInputStream()));
            // Send http request to server and get return data
            // HTTP header
            dataout.writeBytes("POST " + script + " HTTP/1.0\r\n");
            dataout.writeBytes("Content-type: " + ctype + "\r\n");
            dataout.writeBytes("Content-length: " + sdata.length() + "\r\n");
            dataout.writeBytes("\r\n");         // end of header
            // POST data
            dataout.writeBytes(sdata);
            dataout.writeBytes("\r\n");
            boolean body = false;
            String line;
            while ((line = datain.readLine()) != null)
            {
                if (body)
                    rdata += "\n" + line;
                else if (line.equals(""))       // end of header
                    body = true;
            }            // close up shop
            dataout.close();
            datain.close();
        } catch (Exception e){
            e.printStackTrace();
        }
        finally {
            System.out.println(rdata);
            try {
                sock.close();
            } catch(Exception e) {
                e.printStackTrace();
            }       }
    }
}

解决方案 »

  1.   

    模拟浏览器使用post方法向表单发送数据,不用socket编程也能实现。要想知道数据是否正确发送,你需要把从服务器返回的网页保存下来看看就知道了。源码如下:
    import java.net.*;
    import java.io.*;public class URLPost extends Object{
        public static void main(String args[]){
            URL destURL;
            HttpURLConnection urlConn;
            String request;
            try{
               request="loginname=name&password=password";//换成正确的用户名和密码
               destURL = new URL("http://192.168.68.201:8080/");
               urlConn = (HttpURLConnection)destURL.openConnection();
               urlConn.setDoOutput(true);     // 需要向服务器写数据
               urlConn.setDoInput(true);      // 
               urlConn.setUseCaches(false);   // 获得服务器最新的信息
               urlConn.setAllowUserInteraction(false); 
               urlConn.setRequestProperty("Content-type","application/x-www-form-urlencoded");
               // 必须告诉服务器你发送的数据大小. 这也同样告诉 
               urlConn.setRequestProperty("Content-length", ""+request.length());
               // Open an output stream so you can send the info you are posting
               DataOutputStream outStream = new DataOutputStream(urlConn.getOutputStream());
               // Write out the actual request data
               outStream.writeBytes(request);
               outStream.close();
               // Now that you have sent the data, open up an input stream and get
               // the response back from the server try{
               DataInputStream inStream = new DataInputStream(urlConn.getInputStream());
         System.out.println("Print HeaderFile:");
               int i=0;
               while(urlConn.getHeaderField(i)!=null){
                 System.out.println(urlConn.getHeaderFieldKey(i)+" "+urlConn.getHeaderField(i));//输出html头信息
                 i++;
               }
               int ch;
               // Dump the contents of the request to System.out
               while ((ch = inStream.read()) >= 0) {
                    System.out.print((char) ch); //输出html文件体信息           }
               inStream.close();
               }catch(Exception e){System.out.println("error"+e);}
               }catch (Exception e) {
                e.printStackTrace();
            }
        
        
        }
        
    }
      

  2.   

    能不能再解释一下,特别是需要post的数据在哪几行发送的?
      

  3.   

    那个Post的问题我基本上解决了,不过还有一些其它的东西,我还不能搞定,请高手指导,就是Post以后,得到输入流以后如何处理。比如,我现在使用Post方法,使用user=aaa&password=111登陆进入一个网站以后,获得输入流后,我发现服务器在连接线程Session内部写入了一个变量,比如是user=aaa,我还希望继续连接更深入的网页,但是,显然,不能释放HttpURLConnection对象,我该如何访问这些资源?为了说明这个问题,我还想补充一个例子,比如Email邮件忘记密码的修改,先要问你的帐号,比如我通过编程post后,通过输入流获得了下一个网页的内容,下一页问生日,我还需要post,但发现session中写入东西,因此不能重新释放那个HttpURLConnection对象,请问这时我该如何做,做好能稍微详细一点,多谢。
      

  4.   

    要完成这样复杂的操作,用http://www.innovation.ch/java/HTTPClient/这个好
      

  5.   

    呵呵,忘了开代理,冒泡了。我编了一个测试程序,请各位高手给看看吧。import java.io.*;
    import java.net.*;
    import java.util.*;public class URLConnectionTest {
      String urlName = "http://freemail.263.net/cgi/reg?funcid=rpbirthday";
      URL url = null;
      HttpURLConnection connection = null;
      BufferedReader in = null;
      BufferedWriter out = null;
      String guessUsername;  public URLConnectionTest() {
        try {
          //连接263服务器
          url = new URL(urlName);
          connection = (HttpURLConnection)url.openConnection();
          connection.setDoInput(true);
          connection.setDoOutput(true);
          connection.setUseCaches(false);
          connection.setRequestMethod("POST");
          connection.setAllowUserInteraction(false);
          connection.setRequestProperty("Content-type","application/x-www-form-urlencoded");
    //      connection.setRequestProperty("Content-length", ""+request.length());      connection.connect();
          //得到输出流
          out = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
    //      in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
      public String getSid(String userName) {
        String request = "username=" + userName;
        String userSid = null;
        try {
          //向服务器写入注册信息
          out.write(request);
          out.flush();      //得到输入流
          in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
          String line;
          while ((line = in.readLine()) != null) {
            int tmp;
            if ((tmp = line.indexOf("sid")) != -1) {
              //下面加六只是为了编程方便,基于263的文件返回格式
              String tempStr = line.substring(tmp+6);
              StringTokenizer token = new StringTokenizer(tempStr, "\"");
              //呵呵,这里有点懒了
              token.nextToken();
              userSid = token.nextToken();
            }
          }
          in.close();
        } catch (Exception e) {
          e.printStackTrace();
        }
        return userSid;
      }  public String getBirthday() {
        try {
          String request = "year=1978&month=8&day=17";
          out.write(request);
          out.flush();      //得到输入流
          in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
          //上面那个输入流,不论如何都是空的,但是如果不使用getSid函数中的输入流,则此输入流就可正确获得,我想获得两次的输入结果,不知该怎么办      String tempStr;
          while ((tempStr = in.readLine()) != null){
            System.out.println(tempStr);
          }
        } catch (Exception e) {
          e.printStackTrace();
        }    return "OK";
      }
      public static void main(String args[]) {
        URLConnectionTest test = new URLConnectionTest();
        System.out.println(test.getSid("babababa97"));
        System.out.println(test.getBirthday());
      }
    }这个测试程序,先向263那个生日的验证写入一个babababa97的用户名,返回一个新的页面,我得到了这个页面,我现在想继续访问更深入的页面,但是第二次使用获取输入流的时候,发现输入流中的内容为空,请高手帮忙调试一下,看看如何在第二次获取到具有网页内容的输入流。另外,上面代码在jdk1.3可通过,在jdk1.4b,运行时出错。
    请高手指教。
      

  6.   

    不会是JBuilder的问题吧,等我试试,呵呵。高手就是高手,我再试一遍,哈哈。
      

  7.   

    不行呀,路人甲。你用jdk1.3编译并运行,结果是一个RAxAwXIACcbAIoWP类似的东东吧,那个是第一个输入流的结果,就是getSid方法的结果。不过,还有一个getBirthday()方法呢,主要是那个输入流,我无法获得新的结果。我在getBirthday方法中,又Post了几个参数,可是再获得输入流,就发现输入流为空了,该如何办呀。另外,比如我获得了一个页面,然后通过Post获得下一个页面,如何再不断掉Session的情况下获得以前访问的页面呢?