What is wrong with this code?

import java.io.*; import java.net.*; ... URL url = new URL(e.getText().toString()); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); 

If you comment out the last line, nothing happens. If you leave it, the application is compiled, but a message pops up at runtime.

 Π’ ΠΏΡ€ΠΈΠ»ΠΎΠΆΠ΅Π½ΠΈΠΈ "Π₯Π₯Π₯" ΠΏΡ€ΠΎΠΈΠ·ΠΎΡˆΠ»Π° ошибка 

and it closes abnormally.

  • Π’ ΠΏΡ€ΠΈΠ»ΠΎΠΆΠ΅Π½ΠΈΠΈ "Π₯Π₯Π₯" ΠΏΡ€ΠΎΠΈΠ·ΠΎΡˆΠ»Π° ошибка - Is the error itself? - Daniel Shatz
  • @DanielShatz, except for the specified text, nothing was printed, but thanks to your answer (in particular, AsyncTask ), the problem was solved, thanks. - Daniel Kolesnichenko

1 answer 1

The request is sent when getInputStream(); called getInputStream();

Most likely, the error you see tells you that you are making an HTTP request in the main stream of the Android application (if this is not the case, add the question).

Internet queries tend to take a lot of time, and the main thread is designed primarily for processing and displaying the user interface, which must respond to user actions quickly. Therefore, you need to create a new thread:

 Thread t = new Thread(new Runnable(){ public void run(){ //Π’Π°Ρˆ ΠΊΠΎΠ΄ для запроса } }).start(); 

Or, you can use AsyncTask . Read more about it and about streams in general here: https://habrahabr.ru/post/124484/

Note that you cannot do anything with interface elements not from the main thread. To execute code in the main thread, use Activity.runOnUiThread .