采用HttpClient模拟登陆一个WEB系统。代码如下:
package com.inspur;import java.io.IOException;
import java.util.ArrayList;
import java.util.List;import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.cookie.CookieSpec;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;public class Test {

static final String LOGON_SITE = "10.1.98.210";   
  
  
    public static void main(String[] args) throws Exception{   
  
        HttpClient client = new HttpClient();   
  
        client.getHostConfiguration().setHost(LOGON_SITE);
        
//        client.getParams().setParameter("http.protocol.single-cookie-header", true);
        
        client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);        client.getHostConfiguration().setProxy("10.19.67.1",808); 
     
        
        PostMethod post = new PostMethod("http://10.1.98.210/cmcceoms/roles/loginverify.jsp");   
  
        NameValuePair name = new NameValuePair("username", "nstp");       
  
        NameValuePair pass = new NameValuePair("password", "PassWorD");              post.setRequestBody(new NameValuePair[]{name,pass});         int status = client.executeMethod(post);   
       
        System.out.println(post.getResponseBodyAsString()); 
        System.out.println("----------------------------------------------");
  
        post.releaseConnection();   
        
        int statuscode = post.getStatusCode();   
        
        redirect(client,post,statuscode);
//       
//      
       
       //查看cookie信息   
         
        CookieSpec cookiespec = CookiePolicy.getDefaultSpec();   
  
        Cookie[] cookies = cookiespec.match(LOGON_SITE, 80, "/", false, client.getState().getCookies());          if (cookies.length == 0) {   
  
           System.out.println("None");      
  
       } else {   
  
           for (int i = 0; i < cookies.length; i++) {   
  
               System.out.println(cookies[i].toString());      
  
           }   
  
       }   
       
       System.out.println("----------------------------------------------");   
              
       
//  
       //访问所需的页面main2.jsp   
       Cookie[] cookiesss = client.getState().getCookies();   
       client.getState().addCookies(cookiesss);
       GetMethod get = new GetMethod("http://10.1.98.210/cmcceoms/common/jsp/pendingTransactNew.jsp");        get.setRequestHeader("Cookie", cookiesss.toString());      
     int sstatus= client.executeMethod(get);   
       
     int sscode=get.getStatusCode();
  
        System.out.println(get.getResponseBodyAsString());   
  
        get.releaseConnection();   
        
        System.exit(0);
  
    }   
    
    
    public static void redirect(HttpClient client,PostMethod post,int statuscode) throws HttpException, IOException{
      if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) ||   
               
                 (statuscode == HttpStatus.SC_MOVED_PERMANENTLY) ||   
               
                 (statuscode == HttpStatus.SC_SEE_OTHER) ||   
               
                 (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)){    
               
               
                 //读取新的URL地址   
               
                 Header header = post.getResponseHeader("location");   
               
                 if (header != null)   
                 {   
               
                     String newuri = header.getValue();   
               
                     if ((newuri == null) || (newuri.equals("")))   
               
                                newuri = "/";   
               
               
//                     GetMethod redirect = new GetMethod(newuri);   
                     PostMethod redirect =new PostMethod(newuri);
               
                     client.executeMethod(redirect);   
               
                     System.out.println("Redirect:"+   
                              redirect.getStatusLine().toString());   
                     
                     System.out.println(redirect.getResponseBodyAsString());
               
                     redirect.releaseConnection();   
               
                 } else  
               
                      System.out.println("Invalid redirect");   
               
                }
      System.out.println("----------------------------------------------");    }
}
执行时报的日志信息:2010-3-9 16:43:52 org.apache.commons.httpclient.HttpMethodDirector isRedirectNeeded
信息: Redirect requested but followRedirects is disabled
<html><head><title>302 Moved Temporarily</title></head>
<body bgcolor="#FFFFFF">
<p>This document you requested has moved temporarily.</p>
<p>It's now at <a href="http://10.1.98.210/cmcceoms/roles/postcontrol.jsp?username=sd_gongqin&amp;password=PassWorD">http://10.1.98.210/cmcceoms/roles/postcontrol.jsp?username=sd_gongqin&amp;password=PassWorD</a>.</p>
</body></html>----------------------------------------------
Redirect:HTTP/1.1 200 OK<html>
  <head>
  
    <title>工程参数传递</title>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">  </head>
  
  <body>
  <form action="http://10.1.98.210:80/arsys/shared/eomslogin.jsp" id="postform" name="postform" method="post">
   <input type="hidden" id="username" name="username" value="sd_gongqin" />
   <input type="hidden" id="password" name="password" value="PassWorD" />
   <input type="hidden" id="eomsflag" name="eomsflag" value="yes" />
  </form>
    <script type="text/javascript">
document.getElementById("postform").submit();
</script>
  </body>
</html>----------------------------------------------
EOMSJSESSIONID=ssrnLWLBTrw1vqfr6S28Fdlrz62KpBpjw8RjFxGXbxk672xWFVYK!1137324615
----------------------------------------------
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Draft//EN">
<HTML>
<HEAD>
<TITLE>Error 500--Internal Server Error</TITLE>
<META NAME="GENERATOR" CONTENT="WebLogic Server">
</HEAD>
<BODY bgcolor="white">
<FONT FACE=Helvetica><BR CLEAR=all>
<TABLE border=0 cellspacing=5><TR><TD><BR CLEAR=all>
<FONT FACE="Helvetica" COLOR="black" SIZE="3"><H2>Error 500--Internal Server Error</H2>
</FONT></TD></TR>
</TABLE>
<TABLE border=0 width=100% cellpadding=10><TR><TD VALIGN=top WIDTH=100% BGCOLOR=white><FONT FACE="Courier New"><FONT FACE="Helvetica" SIZE="3"><H3>From RFC 2068 <i>Hypertext Transfer Protocol -- HTTP/1.1</i>:</H3>
</FONT><FONT FACE="Helvetica" SIZE="3"><H4>10.5.1 500 Internal Server Error</H4>
</FONT><P><FONT FACE="Courier New">The server encountered an unexpected condition which prevented it from fulfilling the request.</FONT></P>
</FONT></TD></TR>
</TABLE></BODY>
</HTML>在登陆后,访问其他页面时报500错误,好像是cookies没起作用,哪位高手指点一下,十分感谢

解决方案 »

  1.   

    如果cookies没起作用的话是否cookies被防火墙什么东西禁用了呢?不是很清楚..但是cookies这个东西不是很好用  有些客户的机器禁用了cookies那样比较麻烦
      

  2.   

    现在的问题是,模拟登陆后请求新的页面时,得到                                                     <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <title>待办查询</title>
        <link rel="stylesheet" href="http://10.1.98.210:80/cmcceoms/css/stylenull.css" type="text/css" />
    <script src="http://10.1.98.210:80/cmcceoms/scripts/style.js" type="text/javascript"></script>
    <script src="http://10.1.98.210:80/cmcceoms/scripts/datepicker/WdatePicker.js" type="text/javascript"></script>
    <base href="http://10.1.98.210:80/cmcceoms/">
    <script type="text/javascript">
    //修正透明PNG
    fixie6('http://10.1.98.210:80/cmcceoms/');
    //修正窗口
    fixwindow(0,100);
    function tranferPage(type)
    {
         var pageCount=document.getElementById("pageCount").value;
         var pageNumber=document.getElementById("pageNumber").value;
         if(pageNumber=="")
         pageNumber="1";
        
    if(type=="frist")
    {
    if(pageNumber!="1")
    {
         document.getElementById("pageNumber").value="1";
         document.QueryForm.submit();
         }
         }
         else if(type=="previous")
         {
         var intpageNumber=parseInt(pageNumber);
         if(intpageNumber>1)
         {
         intpageNumber--;
        document.getElementById("pageNumber").value=intpageNumber;
         document.QueryForm.submit();    
         }
         }
         else if(type=="next")
         {
         var intpageNumber=parseInt(pageNumber);
         var intpageCount=parseInt(pageCount);
         if(intpageCount>intpageNumber)
         {
         intpageNumber++;
        document.getElementById("pageNumber").value=intpageNumber;
         document.QueryForm.submit();    
         }
        
         }
         else if(type=="end")
         {
         if(document.getElementById("pageNumber").value!=pageCount)
         {
         document.getElementById("pageNumber").value=pageCount;
         document.QueryForm.submit();
         }
         }         
    }
         function ConditionDivSet()
         {
         if(document.getElementById("isfirst").value!="1")
         {
         if(document.getElementById("quary").style.display=="")
         document.getElementById("quary").style.display="none";
         else
         document.getElementById("quary").style.display="";
        }
         }
         function btn_submit()
         {
         document.getElementById("pageNumber").value="1";
         document.QueryForm.submit(); 
         }
         function btn_refurbish()
         {
         document.QueryForm.submit(); 
         }
         function onload()
         {
         document.getElementById("isfirst").value="2";
         if(document.getElementById("isfirst").value=="1")
         {
         //document.getElementById("quary").style.display="";
         }
         else
         {
         //图表显示
         //document.getElementById("rchart").style.display="";
         }
         }
         function ConditionDivSet()
         {
         if(document.getElementById("ConditionDiv").style.display=="")
         document.getElementById("ConditionDiv").style.display="none";
         else
         document.getElementById("ConditionDiv").style.display="";
        
         }    
         function SortQuery(sortFiled)
         {     document.getElementById("txtSortfiled").value=sortFiled;
         if(document.getElementById("sortType").value!="1")
         {
         document.getElementById("sortType").value="1"
         }
       else
       {
       document.getElementById("sortType").value="0"
       }    
         document.QueryForm.submit();
         }    
         function zz_reload()
          {
            document.all.tags("form")[0].submit();
           }
           function EditListCount()
           {
            document.getElementById("pageSize").value = document.getElementById("listCount").value;
            document.QueryForm.submit();
           }
    </script>  </head>  <body onLoad="onload()">                 
        但是页面下面要显示的信息得不到,body里面应该有如下信息:<form name="QueryForm" method="post">    <table width="100%" border="0" cellpadding="0" cellspacing="0" class="tableborder">
       <tr>
    <th>工单主题</th>
        <th>建单时间</th>
        <th>完成期限</th>

       </tr>
      
       <tr class="table_rowcolor1" onDblclick="TRDbOnclick('/arsys/forms/cmcceoms4/WF:EL_UVS_TSK//?eid=000000000004076&processid=000000000164005&processtype=DEAL')" onMouseOver="FocusRow(this)" onMouseOut="BlurRow(this)">
      
       <td align="left">
       <img src="images/default/usual.png" alt="紧急程度:一般">&nbsp;
       [<font color="#000000">任务执行中</font>]
       <a class="itemlink" href="/arsys/forms/cmcceoms4/WF:EL_UVS_TSK//?eid=000000000004076&processid=000000000164005&processtype=DEAL" target="_blank" title="通用任务工单(任务执行中):请各省配合增加策略">
       通用任务工单:请各省配合增加策略
       </a>
           
       </td>
       <td align="left">2010-03-09 16:06:24</td>
       <td align="left">2010-03-12 16:03:38</td>
       </tr>
      
       <tr class="table_rowcolor2" onDblclick="TRDbOnclick('/arsys/forms/cmcceoms4/WF:EL_UVS_TSK//?eid=000000000004039&processid=000000000161102&processtype=DEAL')" onMouseOver="FocusRow(this)" onMouseOut="BlurRow(this)">
      
       <td align="left">
       <img src="images/default/usual.png" alt="紧急程度:一般">&nbsp;
       [<font color="#000000">任务执行中</font>]
       <a class="itemlink" href="/arsys/forms/cmcceoms4/WF:EL_UVS_TSK//?eid=000000000004039&processid=000000000161102&processtype=DEAL" target="_blank" title="通用任务工单(任务执行中):请各省反馈网管网组网调研材料">
       通用任务工单:请各省反馈网管网组网调研材料
       </a>
           
       </td>
       <td align="left">2010-03-08 14:32:04</td>
       <td align="left">2010-03-11 14:31:29</td>
       </tr>
      
      
      
    <script>
    if(typeof parent != 'undefined' && typeof parent.setDbInfor != 'undefined'){
    parent.setDbInfor("2");
    }
    </script>
       </table>
       <br>
       <table style="width:97%;" align="center" border="0" cellpadding="0" cellspacing="1">
       <tr>
       <td>
       <input type="hidden" name="txtSortfiled" value="BaseCreateDate">
       <input type="hidden" name="sortType" value="1">
       <input type="hidden" name="action" value="">
       </td>
       </tr>
       </table>
         </form>
      </body>
    </html>哪位大侠知道是什么原因