2012-06-06 26 views
0

我正在用Java編寫程序,並且我想填寫表單的指定字段,模擬提交點擊,因此得到結果頁面。我正在測試我的想法,網址爲http://stu21.kntu.ac.ir/Login.aspx,它有兩個字段txtusernametxtpassword。我正在嘗試下面的代碼,但它不會爲我返回結果頁面。我該怎麼做 ?這段代碼我錯了什麼?模擬點擊Java中的提交按鈕

 DefaultHttpClient conn = new DefaultHttpClient(); 
     conn = new DefaultHttpClient(); 

     ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>(); 
     pairs.add(new BasicNameValuePair("txtusername", "8810103")); 
     pairs.add(new BasicNameValuePair("txtpassword", "8810103")); 

     HttpPost httpPost = new HttpPost("http://stu21.kntu.ac.ir/Login.aspx"); 
     UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, 
       "UTF-8"); 

     httpPost.setHeader(
       "UserAgent", 
       "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.19 (KHTML, like Gecko) Ubuntu/12.04 Chromium/18.0.1025.151 Chrome/18.0.1025.151 Safari/535.19"); 

     httpPost.setEntity(entity); 
     HttpResponse response = conn.execute(httpPost); 
     InputStream is = response.getEntity().getContent(); 
     RandomAccessFile raf = new RandomAccessFile(
       "/home/hossein/Desktop/random.aspx", "rw"); 
     raf.seek(0); 

     int bytes = 0; 
     byte[] buffer = new byte[1024]; 

     while ((bytes = is.read(buffer)) != -1) 
      raf.write(buffer, 0, bytes); 

     raf.close(); 
     is.close(); 

對不起,如果我的問題與其他線程重複,我無法找到我的解決方案在其他線程。

感謝提前:)

+1

嘗試將它直接指向login.aspx頁面。也許它不是網站的默認頁面 另外,它應該在try catch塊內。打印錯誤堆棧,看看它說了什麼 –

+1

我測試了你的答案,它不起作用: -

+1

你怎麼知道它不起作用?它有什麼作用?或不這樣做? –

回答

3

我認爲你需要HTTPUnit。有一個很好的教程在javaworld

試想一下,在下面的例子有:

public void testGoodLogin() throws Exception { 
    WebConversation  conversation = new WebConversation(); 
    WebRequest request = new GetMethodWebRequest( 
     "http://www.meterware.com/servlet/TopSecret"); 
    WebResponse response = conversation.getResponse(request); 
    WebForm loginForm = response.getForms()[0]; 
    request = loginForm.getRequest(); 
    request.setParameter("name", "master"); 
    response = conversation.getResponse(request); 
    assertTrue("Login not accepted", 
       response.getText().indexOf("You made it!") != -1); 
    assertEquals("Page title", "Top Secret", response.getTitle()); 
} 

我相信你可以做你的測試就是這樣的。

+0

+1使用專爲此作業設計的API。 –