日期:2014-05-20  浏览次数:20671 次

问个可行性的问题,关于模拟post表单的提交问题
下面是我抓OA的一个登陆网页的一个提交表单,我能否写个JAVA应用程序通过socket或者什么http之类的东西来在我的应用程序里面提交账号和密码,我的目的是抓他返回的页面内容,然后做分析。

<form onsubmit="var languages=window.document.all.languages.value;
var Curname=document.forms[0].Username.value;
var Password=document.forms[0].Password.value;
document.cookie = &quot;A=&quot; + Curname;
document.cookie = &quot;B=&quot; + Password;
 
//设置最后访问人
var cookieExpires
var expdate = new Date();
expdate.setTime(expdate.getTime() + 30 * (24 * 60 * 60 * 1000));
cookieExpires = expdate.toGMTString();
if (languages!=&quot;&quot;){
document.cookie = &quot;LN=&quot;+languages+ &quot;;expires=&quot; + cookieExpires;
}
 
document.cookie = &quot;LastVisitUserName=&quot; + Curname + &quot;;expires=&quot; + cookieExpires;
 
 
return true;" method="post" action="/names.nsf?Login" name="_DominoForm">


------解决方案--------------------
Java code

        String currname = "";    //提交的用户名
        String currpwd = "";    //提交的秘密
        
        //post的数据,其中的Username 和 Password 是表单上input的name属性名,大小写必须一致
        String postdata = "Username=" + URLEncoder.encode(currname,"utf-8") +"&Password=" + URLEncoder.encode(currpwd, "utf-8");
        
        URL url = new URL("http://localhost/xxx/names.nsf?Login"); //提交的地址
        
        //STEP.1.建立连接
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("POST");    //设置方法为Post
        
        //STEP.2.设置Cookie 根据你的js做的
        con.setRequestProperty("Cookie", "A="+currname+"; B="+currpwd+"; LastVisitUserName=" + currname +";");
        
        //STEP.3.发送post数据
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(con.getOutputStream()));
        writer.write(postdata);
        writer.flush();
        writer.close();
        
        //STEP.4.获取返回数据
        BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        reader.close();
        
        con.disconnect();