Witam,
klasa pobiera cookies, w tym nk_session, które (jeśli dobrze rozumiem) jest konieczne, aby zalogować użytkownika, następnie przesyła cookies razem z loginem i hasłem (metoda POST), na koniec pobiera stronę, niestety pobiera ponownie stronę logowania, a powinienem dostać stronę główną z zalogowanym użytkownikiem.
Nawet dwu-godzinne zgadywanie nie przyniosło rezultatu, będę wdzięczny za wskazówki gdzie szukać błędu.
public class Browser {
public String getCookies() {
String result = "";
try {
URL url = new URL("http://www.nasza-klasa.pl/login");
// Create a URLConnection object for a URL
URLConnection conn = url.openConnection();
for (int i = 0;; i++) {
String headerName = conn.getHeaderFieldKey(i);
String headerValue = conn.getHeaderField(i);
if (headerName == null && headerValue == null) {
// No more headers
break;
}
if (headerName == null) {
// The header value contains the server's HTTP version
} else {
if (headerName.equals("Set-Cookie")) {
result = headerValue.replace(".nasza", "nasza").trim();
}
if (headerName.equals("Expires")) {
result += "; expires=" + headerValue.trim();
}
}
}
} catch (Exception e) {
System.err.print(e);
}
return result;
}
public String getSite() {
String accept = "*/*";
String user_agent = "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)";
String cookies = "";
cookies = getCookies();
StringBuffer sb = new StringBuffer();
try {
URL url = new URL("http://nasza-klasa.pl/login");
String body = URLEncoder.encode("login", "UTF-8") + "="
+ URLEncoder.encode("użytkownik", "UTF-8") + "&"
+ URLEncoder.encode("password", "UTF-8") + "="
+ URLEncoder.encode("hasło", "UTF-8");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setAllowUserInteraction(false);
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(true);
conn.setRequestProperty("User-Agent", user_agent);
conn.setRequestProperty("Accept", accept);
conn.setRequestProperty("Refferer", "http://nasza-klasa.pl/login");
conn.setRequestProperty("Connection", "Keep-Alive");
// Set the cookie value to send
conn.setRequestProperty("Cookie", cookies);
// the content-length
conn.setRequestProperty("Content-length", Integer.toString(body
.length()));
// the Content-type
conn.setRequestProperty("Content-type",
"application/x-www-form-urlencoded");
// get the output stream to POST our form data
OutputStreamWriter wr = new OutputStreamWriter(conn
.getOutputStream(), "UTF8");
wr.write(body);
System.out.print(body);
wr.flush();
wr.close();
InputStream rawInStream = conn.getInputStream();
// get response
BufferedReader rdr = new BufferedReader(new InputStreamReader(
rawInStream));
String line;
while ((line = rdr.readLine()) != null) {
sb.append(line);
System.out.println(line);
}
return sb.toString();
} catch (Exception e) {
System.out.println("Exception " + e.toString());
e.printStackTrace();
}
return ""; // exception occurred
}
}
--
Jakub