2

Does anyone know how I can make a synchronous call via android? I basically do not want to continue any further until I get the response back y/n from the server.

This is the simplest version of the code that I have

URL url = new URL("http://google.com");
HttpURLConnection connection = (HttpURLConnection) 
url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();

But it gives me this error because it is created on the main thread.

NetworkOnMainThreadException

Any help is greatly appreciated, thanks

flashc5
  • 307
  • 1
  • 6
  • 16

1 Answers1

3

Basically you can not do HTTP calls on MainThread.

There are many way arounds like Create a Runnable thread or AsyncTask etc. Try the following code snippet:

new Thread(new Runnable()
    {
        public void run()
        {
            try
            {
              //your HTTP request code..      
            }
            catch (IOException e)
            {
                //Handle exceptions
                e.printStackTrace();
            }
        }
    }).start();

For further reading multithreading see the Android Developer documentation.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
Akshay
  • 1,161
  • 1
  • 12
  • 33
  • @GhostCat I did'nt quite get you..This code will be a guideline for OP.Rest things OP should handle.It's just a hint or reference – Akshay Aug 29 '17 at 06:31
  • From what i read, I am forced to create a thread. so what is wrong with @akshay response? Also the answer you provided is in turkish, I dont talk turkey, well not usually anways. – flashc5 Aug 29 '17 at 06:37
  • 2
    Much better now. I took the freedom and slightly updated your answer. And: consider deleting no longer required comments. In case you want to say thank you, I guess you know where to find my answers or questions ;-) – GhostCat Aug 29 '17 at 07:01
  • @flashc5 Correct. Now things look much better. – GhostCat Aug 29 '17 at 07:06