Java-класс, использующий HttpUrlConnection, генерирует IOException, не может читать или писать - PullRequest
0 голосов
/ 29 мая 2019

Я создал этот класс, который обрабатывает вход в систему с помощью HttpUrlConnection и HttpsUrlConnection:

import java.io.*;
import java.net.*;
import javax.net.ssl.*;

public class HttpLogin
{
    public String text;

    String host;
    int port;
    String uri;
    String user_p;
    String pass_p;
    String username;
    HttpURLConnection connection = null;
    HttpsURLConnection secure_connection = null;
    URL url;

    String method = "GET";


    public HttpLogin(String host, int port, String uri, String user_p, String pass_p, String username, String http_method)
    {
        this.host = host;
        this.port = port;
        this.uri = uri;
        this.user_p = user_p;
        this.pass_p = pass_p;
        this.username = username;
        this.method = http_method; 
        try{
            this.url  = new URL(host);        
        }
        catch(IOException e)
        {
            this.url = null;
        }
    }

    public void sendlogin(String password) throws IOException
    {
        if(this.host.startsWith("https://") == true)
        {   try{
                do{
                  this.secure_connection = getSecureUrlConnection();
                  this.secure_connection.connect();
                 }while(this.secure_connection == null);    

                sendSecureRequest(password);
                this.text = getSecureResponse();                    
            }
            catch(IOException e)
            {
                this.secure_connection.disconnect();
                return;
            }
        }
        else if(this.host.startsWith("http://") == true)
        {   
            try{
                do{
                    this.connection = getUrlConnection();
                    this.connection.connect();
               }while(this.connection == null);

               sendRequest(password);  
               this.text = getResponse();
            }
            catch(IOException e)
            {
                this.connection.disconnect();
                return;
            }
        }
    }

    private HttpURLConnection getUrlConnection()
    {
        try
        {
            return (HttpURLConnection) url.openConnection();
        }
        catch(NullPointerException | IOException e)
        {
            System.out.println("Cannot resolve hostname: " + host);
            return null;
        }
    }

    private HttpsURLConnection getSecureUrlConnection()
    {
        try
        {
            return (HttpsURLConnection) url.openConnection();
        }
        catch(NullPointerException | IOException e)
        {
            System.out.println("Cannot resolve hostname: " + host);
            return null;
        }
    }

    private String getResponse()
    {
        try{
            BufferedReader br = new BufferedReader(new InputStreamReader(this.connection.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String temp;
            while((temp = br.readLine()) != null)
            {
                sb.append(temp);
            }
            br.close();
            return sb.toString();
        }
        catch(IOException e)
        {
            System.out.println("Error in reading");
            connection.disconnect();
            return null;                
        }
    }

    private String getSecureResponse()
    {
        try{
            BufferedReader br = new BufferedReader(new InputStreamReader(this.secure_connection.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String temp;
            while((temp = br.readLine()) != null)
            {
                sb.append(temp);
            }
            br.close();
            return sb.toString();
        }
        catch(IOException e)
        {
            System.out.println("Error in reading");
            this.secure_connection.disconnect();
            return null;                
        }
    }

    private void sendSecureRequest(String password) throws IOException
    {
        String body = user_p+"="+username+"&"+pass_p+"="+password;
        this.connection.setDoOutput(true);
        this.connection.setRequestMethod(this.method);
        this.connection.setInstanceFollowRedirects(true);
        this.connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        this.connection.setRequestProperty("Content-Lenght", Integer.toString(body.length()));
        OutputStreamWriter sw = new OutputStreamWriter(this.connection.getOutputStream());
        sw.write(body);
        sw.close();
    }

    private void sendRequest(String password) throws IOException
    {
        String body = user_p+"="+username+"&"+pass_p+"="+password;
        this.secure_connection.setDoOutput(true);
        this.secure_connection.setRequestMethod(this.method);
        this.secure_connection.setInstanceFollowRedirects(true);
        this.secure_connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        this.secure_connection.setRequestProperty("Content-Lenght", Integer.toString(body.length()));
        OutputStreamWriter sw = new OutputStreamWriter(this.secure_connection.getOutputStream());
        sw.write(body);
        sw.close();
    }

    public Boolean isLogin()
    {   
        if(this.connection != null)
        {
            String header = this.connection.getHeaderField("location");
            try{
                if(header.equals(this.uri) == false)
                {
                    return true;
                }
            }
            catch(NullPointerException e)
            {
                return false;
            }  
        } 
        else if(this.secure_connection != null)
        {
            String header = this.secure_connection.getHeaderField("location");
            try{
                if(header.equals(this.uri) == false)
                {
                    return true;
                }
            }
            catch(NullPointerException e)
            {
                return false;
            }  
        } 
       return false;
    }
}

Но когда я проверяю его, это дает мне IOException, исключение обрабатывается некоторыми методами, которые закрывают соединение.

Если я пытаюсь использовать этот класс и выполнить вход в систему, он выводит «Ошибка чтения».

В чем проблема? Я не могу читать и не писать в этот UrlConnection.

EDIT:

Это трассировка стека исключенного исключения:

java.io.IOException: Server returned HTTP response code: 403 for URL: https://example.com
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
        at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
        at HttpLogin.getSecureResponse(HttpLogin.java:122)
        at HttpLogin.sendlogin(HttpLogin.java:49)
        at Test.main(Test.java:13)

Я отредактировал URL в трассировке стека до https://example.com

РЕДАКТИРОВАТЬ 2:

Я изменил параметры для входа в систему, и теперь исключение не выдается, и функция isLogin() возвращает true. Но ответ никогда не бывает красным. И текст переменной пуст.

...