2010-12-16 34 views
3

我正在研究一个需要登录到ASP.NET Web窗体的Java程序,然后一旦通过身份验证,就下载一个文件。正常的HTTP GET/POST不是问题,但是当我从java连接,但它来自浏览器时,ASP似乎不给我一个SESSION ID。登录到ASP.NET Web窗体的Java方法

当我查看Firefox中的标题信息时,发现初始登录时cookie被设置,但是该页面立即被重定向到一个新的URL。我不确定它是否重要,但登录后重定向到的页面包含iframe。我已经尝试加载主页面和iframe src里面,但都没有给我头中的cookie。

//Pull up the login page, extract out the hidden input variables __VIEWSTATE, __EVENTVALIDATION 
URL url = new URL(loginPage); 
HttpURLConnection conn = null; 
conn = (HttpURLConnection) url.openConnection(); 
//This reads the page line-by-line and extracts out all the values from hidden input fields 
Map<String,String> formFields = getViewstate(conn); 

//Now re-open the URL to actually submit the POST data 
conn = (HttpURLConnection) url.openConnection();    
conn.setRequestMethod("POST"); 
conn.setDoOutput(true); 
conn.setDoInput(true); 
DataOutputStream out = new DataOutputStream(conn.getOutputStream()); 
String postValues = URLEncoder.encode("txtUsername", "UTF-8") + "=" + URLEncoder.encode(uid, "UTF-8"); 
postValues += "&" + URLEncoder.encode("txtPassword", "UTF-8") + "=" + URLEncoder.encode(pwd, "UTF-8"); 
postValues += "&" + URLEncoder.encode("__EVENTTARGET", "UTF-8") + "=" + URLEncoder.encode("", "UTF-8"); 
postValues += "&" + URLEncoder.encode("__VIEWSTATE", "UTF-8") + "=" + URLEncoder.encode(formFields.get("viewstate"), "UTF-8"); 
postValues += "&" + URLEncoder.encode("__EVENTVALIDATION", "UTF-8") + "=" + URLEncoder.encode(formFields.get("eventvalidation"), "UTF-8"); 
out.writeBytes(postValues); 
out.flush(); 
out.close(); 
//At this point looking at Firefox sniffer data, it should be sending back the cookie 
//However there is no Set-Cookie in the header fields 
for (int i = 1; (key = conn.getHeaderFieldKey(i)) != null; i++) { 
     // get ASP.NET_SessionId from cookie 
    if (key.equalsIgnoreCase("set-cookie")) { 
     sessionId = conn.getHeaderField(key); 
     sessionId = sessionId.substring(0, sessionId.indexOf(";")); 
    } 
} 
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
while ((line = rd.readLine()) != null) { 
    //The page it prints out is the page it was redirected to when logged in through the browser 
    System.out.println(line); 
} 
rd.close(); 
//At this point, it was a successful login, but I never got the cookie so I'm stuck 

回答

0

它看起来像您试图访问的网站依赖于HttpURLConnection不支持的Cookie。解决这个问题的一个方法是使用模拟浏览器的类似HtmlUnit的库(支持cookie,javascript等)。

+1

我应该可以解析出标题来提取cookies,对不对?我得到了所有返回的标准头文件,但没有cookie。除非可能我需要明确告诉服务器,否则我接受cookies – 2010-12-16 19:38:15

+0

最后一点是很好的一点,我认为大多数服务器都有一些机制来测试是否支持cookie。我知道Weblogic会在第一个请求的URL和cookie中设置会话ID,然后在下一个请求中将URL值与预期的cookie进行比较,如果匹配,则会丢弃URL编码的ID。如果你得到的cookie,你发回它?你有跟随重定向设置为真?更高层次的图书馆仍然可能是您不需要大量自定义代码即可完成自己想要的任务的最佳选择。 – mezmo 2011-01-06 14:52:50

2

HttpClient,我相信HtmlUnit是基于,具有较低级别的功能,我认为你正在寻找。很好地处理饼干,但如果您需要更多,则Kurt正确地认为您应该寻找具有更多功能的东西。如果您确实需要获得完整的浏览器功能,您可以尝试一些像Selenium/Webdriver这样的程序,它可以在程序控制下自动实现浏览器的自动化。