3

私は、ASP.NET Webフォームにログインする必要があるJavaプログラムに取り組んでおり、認証されたらファイルをダウンロードします。通常の HTTP GET/POST は問題ありませんが、Java から接続したときに ASP が SESSION ID を提供していないように見えますが、それはブラウザからのものです。

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
4

2 に答える 2

2

HtmlUnit が基づいていると私が信じている HttpClient には、あなたが探していると思う低レベルの機能があります。クッキーを適切に処理しますが、さらに必要な場合は、より多くの機能を備えたものを探す必要があるという点で、Kurt は正しい. 実際にブラウザの機能を完全に利用する必要がある場合は、プログラム制御の下でブラウザを実際に自動化する Selenium/Webdriver のようなものを試すことができます。

于 2010-12-16T17:44:16.240 に答える
0

アクセスしようとしているサイトは、HttpURLConnection でサポートされていない Cookie に依存しているようです。この問題を回避するには、ブラウザをシミュレートするHtmlUnitなどのライブラリを使用します(Cookie、JavaScript などをサポートします)。

于 2010-12-16T17:28:49.267 に答える