E
E
Egor Pavlov2018-06-14 07:43:36
Java
Egor Pavlov, 2018-06-14 07:43:36

How to get data from an http request if you need to enter a login with a password when logging in?

I want to get data with an http request, but when entering the site, you need to enter a password and login. Gives error 401
Here is the code:

HttpURLConnection connection = null;
        try {
            connection = (HttpURLConnection) new URL(query).openConnection();

            connection.setRequestMethod("GET");
            connection.setUseCaches(false);
            connection.setConnectTimeout(250);
            connection.setConnectTimeout(250);

            connection.connect();

            StringBuilder sb = new StringBuilder();

            if(HttpURLConnection.HTTP_OK == connection.getResponseCode()){
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

                String line;
                while ((line = in.readLine()) !=null) {
                    sb.append(line);
                    sb.append("\n");
                }
                System.out.println(sb.toString());
            }else{
                System.out.println("fail :" + connection.getResponseCode());
            }
        }catch (Throwable cause){
            cause.printStackTrace();
        }finally {
            if (connection != null){
                connection.disconnect();

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question