0

Hey i'm using HttpUrlConnection in my app. And it's seems to me that every time when I'm making call as .getInputStream() or urlConnection.getResponseCode() etc it makes another request, so it is not good for me, when i'm making POST request. Is there a way to get some kind of response object which encapsulates response data and can be accessible from UI thread, something like this:

private class RegisterAsync extends AsyncTask<String, Void, HttpResponse> {

        protected String doInBackground(String... strings) {
            HttpURLConnection urlConnection = null;
            String message = null;
            try {
                URL url = new URL(REGISTER_URL);
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setDoOutput(true);
                urlConnection.setChunkedStreamingMode(0);
                OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
                out.write(strings[0].getBytes("UTF-8"));
                out.flush();
                out.close();
                HttpResponse response = urlConnection.getResponse();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                urlConnection.disconnect();
            }
            return Response;
        }

        protected void onPostExecute(HttpResponse response) {
            //Do some with response object: get status, headers, content etc?
        }
    }
Vadym Kovalenko
  • 699
  • 1
  • 11
  • 27

1 Answers1

0

you can do the following steps:

  1. Create the webservice call in a singleton class
  2. Parse the response and encapsulate it in a custom object(made by you) and save the parsed object into the singleton as instance object.
  3. After this, you can simply send a broadcast message to your activity to let it know that the parsed data is available in the singleton
  4. the onReceive() method of BroadcastReceiver runs on UI thread so you can quickly update your UI there..

After you implement that you can simply call the singleton webservice call method from your activity right after you register to the intent that will be sent from the singleton...

Cata
  • 11,133
  • 11
  • 65
  • 86