Android: reader.readLine() возвращает НУЛЬ

#android #bufferedreader

#Android #bufferedreader

Вопрос:

Метод устанавливает HTTP-соединение, но при чтении данных reader.readLine() returns NULL .

    protected String doInBackground(String... strings) {


        try {

            // Enter URL address where your php file resides
            url = new URL("http://makemyweb.xyz/mobile/login.inc.php");
            Log.d(TAG, "Connected to "  url);
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "exception";
        }

        try {
            // Setup HttpURLConnection class to send and receive data from php and mysql
            conn = (HttpURLConnection)url.openConnection();
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestMethod("GET");

            // setDoInput and setDoOutput method depict handling of both send and receive
            conn.setDoInput(true);
            conn.setDoOutput(true);

            // Append parameters to URL
            Uri.Builder builder = new Uri.Builder()
                    .appendQueryParameter("email", strings[0])
                    .appendQueryParameter("pass", strings[1]);
            String query = builder.build().getEncodedQuery();
            Log.d(TAG, "Q: " query);
            // Open connection for sending data
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();
            conn.connect();

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return "exception";
        }

        try {
            int response_code = conn.getResponseCode();

            // Check if successful connection made
            if (response_code == HttpURLConnection.HTTP_OK) {

                // Read data sent from server
                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder result = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }
                // Pass data to onPostExecute method
                return(result.toString());
            }else{
                return("unsuccessful");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "exception";
        } finally {
            conn.disconnect();
        }

    }
  

Ответ №1:

Я попробовал ваш код, и он не возвращает значение null. Вот полный код:

 private final String TAG = this.getClass().getSimpleName();
private URL url;
private HttpURLConnection conn;
private static final int READ_TIMEOUT = 10_000;
private static final int CONNECTION_TIMEOUT = 10_000;

private void testConnection() {
    AsyncTask<String, Integer, String> asyncTask = new AsyncTask<String, Integer, String>() {
        protected String doInBackground(String... strings) {
            try {
                // Enter URL address where your php file resides
                url = new URL("http://makemyweb.xyz/mobile/login.inc.php");
                Log.d(TAG, "Connected to "   url);
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return "exception";
            }

            try {
                // Setup HttpURLConnection class to send and receive data from php and mysql
                conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(READ_TIMEOUT);
                conn.setConnectTimeout(CONNECTION_TIMEOUT);
                conn.setRequestMethod("GET");

                // setDoInput and setDoOutput method depict handling of both send and receive
                conn.setDoInput(true);
                conn.setDoOutput(true);

                // Append parameters to URL
                Uri.Builder builder = new Uri.Builder()
                        .appendQueryParameter("email", strings[0])
                        .appendQueryParameter("pass", strings[1]);
                String query = builder.build().getEncodedQuery();
                Log.d(TAG, "Q: "   query);
                // Open connection for sending data
                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));
                writer.write(query);
                writer.flush();
                writer.close();
                os.close();
                conn.connect();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                return "exception";
            }

            try {
                int response_code = conn.getResponseCode();

                // Check if successful connection made
                if (response_code == HttpURLConnection.HTTP_OK) {

                    // Read data sent from server
                    InputStream input = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    StringBuilder result = new StringBuilder();
                    String line;

                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }
                    // Pass data to onPostExecute method
                    return (result.toString());
                } else {
                    return ("unsuccessful");
                }
            } catch (IOException e) {
                e.printStackTrace();
                return "exception";
            } finally {
                conn.disconnect();
            }

        }

        @Override
        protected void onPostExecute(String s) {
            Log.d(TAG, "result : "   s);
        }
    };

    asyncTask.execute("someemail@someweb.com", "password");
}
  

И убедитесь, что вы включили

 <uses-permission android:name="android.permission.INTERNET" />
  

в вашем файле манифеста