J
J
Jsman2016-11-17 21:02:05
Java
Jsman, 2016-11-17 21:02:05

How to get authorized?

You need to get the content of the page, but before getting the page you need to enter a username and password, I can’t figure out how to do this using Java, teach me, please tell me.
Blocked on google :(

public class qu {
    public static void main(String args[]) throws IOException {
        String line;
        String result = "";

        URL link = new URL("URL");
        HttpURLConnection conn = (HttpURLConnection) link.openConnection();

        conn.setRequestMethod("GET");


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

        while ((line = rd.readLine()) != null) {
            result += line;
        }

        conn.disconnect();

        System.out.println(result);
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim, 2016-11-18
@z17

In the general case - see what the login form is, usually it's a POST request somewhere with a username and password.
You make the same request in the code, save the response (headers, cookies). Further, when receiving the content of the desired page, substitute these headers and cookies in the request.
In short, you need to imitate a real user with your requests.

I
ivanessence, 2016-11-18
@ivanessence

Here is an approximate piece of code for authorization, if, for example, you also need to click on the button in addition to entering the login and password, then try adding another appendQueryParameter parameter, which can be viewed through F12 on the site where the post goes, button parameters

URL url = new URL(URL_LOGIN_TEST);
            Log.i("connSuccess", "1");
//            CookieHandler.setDefault(manager);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            Log.i("connSuccess", "2");
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            Log.i("connSuccess", "3");
//            conn.setRequestProperty("Cookie",
//                    TextUtils.join(";", manager.getCookieStore().getCookies()));
//            Log.i("COOKIE", manager.getCookieStore().getCookies().toString());
            Log.i("connSuccess", "4");
            Uri.Builder builder = new Uri.Builder()
                    .appendQueryParameter("password", password).appendQueryParameter("email", login);
            String query = builder.build().getEncodedQuery();

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();
            conn.connect();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question