Good morning everyone! The problem lies in the choice of the method: I need to take some JSON, which is sent to the server API (Node.js will return JSON by SQL-query to the database). Perhaps this is all that is required.

First, is it enough that the server only accepts the request and in response returns information on the request? How is it in terms of security?

And how on the android send such a request and how to wait for an answer in the form of what I need?

  • There are libraries Retrofit and similar, which will greatly facilitate the communication of the application with the network - pavlofff

1 answer 1

Enough or not - depends on what the service gives. If it is public data, it makes no sense to close them. If private, you can use the secret key, as most web services do.

It is sent in the same ways as in any other java-program. And as in any other java-program (excluding, perhaps, console utilities) it is worth doing it in the background thread. In Android, there is AsyncTask and Handler for this. The choice of one of them depends on the features of your program. An example of using AsyncTask:

private class GetJsonTask extends AsyncTask<URL, String, JSONObject> { @Override protected JSONObject doInBackground(URL... urls) { //Фоновый поток HttpURLConnection connection = (HttpURLConnection)urls[0].openConnection(); try { ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream in = connection.getInputStream(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new IOException(connection.getResponseMessage()); } int bytesRead = 0; byte[] buffer = new byte[1024]; while ((bytesRead = in.read(buffer)) > 0) { out.write(buffer, 0, bytesRead); } out.close(); return new JSONObject(out.toString()); } finally { connection.disconnect(); } } @Override protected void onPostExecute(JSONObject json) { //Callback в главном потоке //Делайте с вашим json всё, что нужно. } } new GetJsonTask().execute(new URL('http://myservice.ru/somedata.json')); 
  • one
    Starting with Android 3.0, you will not be able to work with the network in the main thread, you will instead get NetworkOnMainThreadExeption. So you don’t have to choose too much :) It would be possible to mention libs like Retrofit. Work with the network in a real application through your own classes, when there is a Retrofit like that .. old school - pavlofff
  • one
    I firmly believe that the newcomer must first deal with basic functions, and only then begin to facilitate his life. - Sergey Gornostaev
  • The basic functions come from Java: java.net.Socket, java.lang.Thread. - tse
  • @tse and they would also be nice to know. - Sergey Gornostaev
  • There is always a balance between digging into theory and writing working applications. Android is so complex that in some cases you have to perform some actions as rituals, and only with time to delve into their essence. - tse