2012-03-31 107 views
2

这是我的代码:无法发送HTTP发送请求到登录表单?

public static String sendPostRequest(String url) { 

    StringBuffer sb = null; 

    try { 

     String data = URLEncoder.encode("user", "UTF-8") + "=" 
       + URLEncoder.encode("username", "UTF-8") + "&" 
       + URLEncoder.encode("password", "UTF-8") + "=" 
       + URLEncoder.encode("password", "UTF-8"); 

     System.out.println(data); //Just to check if data is correct 

     URL requestUrl = new URL(url); 
     HttpURLConnection conn = (HttpURLConnection) requestUrl 
       .openConnection(); 
     conn.setDoOutput(true); 
     conn.setDoInput(true); 
     conn.setRequestMethod("POST"); 

     DataOutputStream osw = new DataOutputStream(conn.getOutputStream()); 
     osw.writeBytes(data); 
     osw.flush(); 

     BufferedReader br = new BufferedReader(new InputStreamReader(
       conn.getInputStream())); 

     String in = ""; 
     sb = new StringBuffer(); 

     while ((in = br.readLine()) != null) { 
      sb.append(in + "\n"); 
     } 

     osw.close(); 
     br.close(); 
    } catch (UnsupportedEncodingException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (MalformedURLException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    return sb.toString(); 
} 

但每当我试图通过这个HTTP POST请求登录,它返回的HTML代码,这始终是一个包含了网站,而不是我的特定HTML代码,该网页上我的用户页面。在HTML登录表单是这样的:

<td width="100" align="left"><span class="texte_listing_bold">Login:</span></td> 
    <td width="300" align="center"><input class="form_size1" type="text" name="user"></td> 
    </tr> 
    <tr> 
    <td width="100" align="left"><span class="texte_listing_bold">Password:</span></td> 
    <td width="300" align="center"><input class="form_size1" type="password" name="password"></td> 
    </tr> 
    <tr> 
    <td colspan="2" align="center"> 
     <input type="hidden" name="login_action" value="true"> 
     <input class="bouton_nosize" type="submit" value="Login"> 
    </td> 

通常的按钮具有name元素,我可以通过我的代码,它不工作,让我登录到这样的网站称那些为好,但这韩元因某种原因工作。这是什么原因?

+0

你包裹该HTML到一个? – 2012-03-31 15:24:44

回答

2

此登录形式使用具有值true称为login_action一个隐藏的输入字段。

你需要通过在您的要求输入用户名和密码一起。

只要确保你提供了所有必要的信息。 您可以使用HTTP嗅探器检查浏览器发送的内容,但最好的方法是查看您尝试进行身份验证的页面源。

如果你没有在Web服务器登录页面源,那么你可能根本不应该写在首位的代码访问或控制。身份验证机制将来可能会发生变化,并且对于脚本(如您正在编写的脚本)可能存在许多安全限制,因为通常不会允许漫游器登录到用户页面和Web报废内容。

+0

哈哈哈我笑了,因为读这之前,从字面上30秒我尝试使用Wireshark嗅探并发现它一起被称为login_action true值过滤捕获的数据包,只显示开机自检后输入字段传递...但感谢,要是我不不会用wireshark你的答案肯定会救我的屁股! – ZimZim 2012-03-31 15:41:50