Java – HTTP requests on Android

HTTP requests on Android… here is a solution to the problem.

HTTP requests on Android

I

was completely desperate, which is why I asked you for help. I have the following code in the android app:

public void OnButtonClick(View view) throws ClientProtocolException, IOException, Exception
{       
    URL yahoo = new URL("http://privyrobsi.sk/brigades/getBrigades.json");
    URLConnection yc = yahoo.openConnection();
    BufferedReader in = new BufferedReader(
                            new InputStreamReader(
                            yc.getInputStream()));
    String inputLine;

EditText ET = (EditText) findViewById(R.id.editText2);
    while ((inputLine = in.readLine()) != null) ET.setText(ET.getText()+inputLine);         
    in.close();        
}

I started with here Got this code, I just modified it slightly.
When I try to run the code as a standalone Java application, it works fine. But when I tried to use it in android, the emulator said unfortunately, the app stopped.
I saved the log from LogCat here .
I ALSO HAVE USES-PERMISSION ANDROID:NAME=”ANDROID.PERMISSION.INTERNET” IN MY LIST FILE.

Solution

You cannot perform network operations in the main thread. In do this in asynctask.

Update:

Your logcat data shows that you have a NetworOnMainThreadException. According to

doc

The exception that is thrown when an application attempts to perform a networking operation on its main thread.

This is only thrown for applications targeting the Honeycomb SDK or
higher. Applications targeting earlier SDK versions are allowed to do
networking on their main event loop threads, but it’s heavily
discouraged.

Solution:

As I already mentioned, you have to use different threads to perform network operations. You can use the following

  1. Asynchronous tasks
  2. Different worker threads
  3. Responsible person

Check this thread . The answer to this question covers almost all solutions

Related Problems and Solutions