Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Sync or Async HTTP Post/Get

Tags:

android

http

I need Sync or Async HTTP Post/Get to get HTML data from Web-Service. I search this whole internet but I can't give good result.

I tried to use this examples:

  • Android Series get/post and multipost requests
  • Jcabi.com
  • Execute HTTP Post request in android

but nothing of them working for me.

HttpClient and HttpGet is cross out, error is :

"org.apache.http.client.HttpClient is deprecated "

Code:

try
{
    HttpClient client = new DefaultHttpClient();
    String getURL = "google.com";
    HttpGet get = new HttpGet(getURL);
    HttpResponse responseGet = client.execute(get);
    HttpEntity resEntityGet = responseGet.getEntity();
    if (resEntityGet != null)
    {
        //do something with the response 
    }
}
catch (Exception e)
{
    e.printStackTrace();
}
like image 443
Avtandil Kavrelishvili Avatar asked Jun 19 '15 11:06

Avtandil Kavrelishvili


People also ask

Is HTTP POST synchronous or asynchronous?

HTTP is a synchronous protocol. The client sends a request and waits for a response from the service. That's independent of the client code execution that could be synchronous (thread is blocked) or asynchronous (thread isn't blocked, and the response will reach a callback eventually).

How do you make asynchronous HTTP request?

Ajax is the traditional way to make an asynchronous HTTP request. Data can be sent using the HTTP POST method and received using the HTTP GET method. To make an HTTP call in Ajax, you need to initialize a new XMLHttpRequest() method, specify the URL endpoint and HTTP method (in this case GET).

What is synchronous and asynchronous HTTP request?

Synchronous request — (Default) Where the client blocks and waits for the result of the remote request before continuing execution. Asynchronous request — Where the client continues execution after initiating the request and processes the result whenever the AppServer makes it available.

Is HTTP request asynchronous?

The HTTP asynchronous request-response behavior is asynchronous only because IBM® App Connect Enterprise treats the request and the response as such, enabling the message flow to retrieve the next message without waiting for the response from the asynchronous request.


2 Answers

The example I have posted below is based on an example that I found on the Android Developer Docs. You can find that example HERE, look at that for a more comprehensive example.

You will be able to make any http requests with the following

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends Activity {
    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new DownloadTask().execute("http://www.google.com/");
    }

    private class DownloadTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            //do your request in here so that you don't interrupt the UI thread
            try {
                return downloadContent(params[0]);
            } catch (IOException e) {
                return "Unable to retrieve data. URL may be invalid.";
            }
        }

        @Override
        protected void onPostExecute(String result) {
            //Here you are done with the task
            Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
        }
    }

    private String downloadContent(String myurl) throws IOException {
        InputStream is = null;
        int length = 500;

        try {
            URL url = new URL(myurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.connect();
            int response = conn.getResponseCode();
            Log.d(TAG, "The response is: " + response);
            is = conn.getInputStream();

            // Convert the InputStream into a string
            String contentAsString = convertInputStreamToString(is, length);
            return contentAsString;
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }

    public String convertInputStreamToString(InputStream stream, int length) throws IOException, UnsupportedEncodingException {
        Reader reader = null;
        reader = new InputStreamReader(stream, "UTF-8");
        char[] buffer = new char[length];
        reader.read(buffer);
        return new String(buffer);
    }
}

You can play around with the code to suit your needs

like image 98
the-ginger-geek Avatar answered Oct 06 '22 01:10

the-ginger-geek


You can use Volley which gives you everything you need. If you decide to use AsyncTask and program it yourself, I'd recommend to not have AsyncTask inside your Activity, but rather put it in a wrapper class and use a callback to that. This keeps your Activity clean and makes the network code reusable. Which is more or less what they did in Volley.

like image 22
Christine Avatar answered Oct 05 '22 23:10

Christine