Http requests in Android
Updated in AndroidAndroid platform contains great support for interacting with different network
services. This tutorial show how to make a basic GET request to a server and
parse the returned contents. This is just a basic example and further more
specific actions are covered in another tutorials. This tutorial processes the
request in an AsyncTask
instance, so if that class isn’t familiar you should
check my tutorial about
it before proceeding.
Basics
Android contains multiple classes like HttpClient
, AndroidHttpClient
and
HttpUrlConnection
which are able to send requests to the Internet. According
to Jesse Wilson
from the Dalvik team HttpUrlConnection
is the one you should use these days and so this tutorial is based on that
class. The example below shows how you can request a web page from a server
and then parse the returned contents. The listing below doesn’t include the
whole project source code, but there’s a link to it on the end of this
document.
Example
package com.tanelikorri.android.httprequest;
import android.app.AlertDialog.Builder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import androidx.appcompat.app.AppCompatActivity;
public class HttpRequestActivity extends AppCompatActivity {
private static final String TAG = "HttpRequestActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_http_request);
}
public void onStartRequestClick(View view) {
// Start a background task which handles the page fetching
new FetchTask().execute();
}
private class FetchTask extends AsyncTask<Void, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Show progressbar
setProgressBarIndeterminateVisibility(true);
}
@Override
protected String doInBackground(Void... params) {
try {
URL url = new URL("https://www.tanelikorri.com/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Log the server response code
int responseCode = connection.getResponseCode();
Log.i(TAG, "Server responded with: " + responseCode);
// And if the code was HTTP_OK then parse the contents
if (responseCode == HttpURLConnection.HTTP_OK) {
// Convert request content to string
InputStream is = connection.getInputStream();
String content = convertInputStream(is, "UTF-8");
is.close();
return content;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private String convertInputStream(InputStream is, String encoding) {
Scanner scanner = new Scanner(is, encoding).useDelimiter("\\A");
return scanner.hasNext() ? scanner.next() : "";
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Hide progressbar
setProgressBarIndeterminateVisibility(false);
if (result != null) {
// Create a dialog
Builder builder = new Builder(HttpRequestActivity.this);
builder.setMessage(result.substring(0, 200) + "...");
builder.setPositiveButton("OK", null);
// and show it
builder.create().show();
}
}
}
}
The whole beef starts from the onStartRequestMethod, it creates a new
FetchTask
AsyncTask
and starts the request execution. FetchTask creates a
new URL
instance that points to https://www.tanelikorri.com/ and then opens the
connection to it.
After the connection has been opened, some simple error checking is made. If the
server returned with a HTTP OK code the InputStream
is converted to a String
instance. The conversion is done with the help of the java.util.Scanner class,
if you’re interested I’ve written a short tutorial
about the InputStream conversion.
After the conversion is done and the result is returned, the first 200
characters of the result is shown to the user with an AlertDialog
. This is how
a simple get request is sent and handled with the HttpUrlConnection
class.
Screenshots
Source code
The source code for this whole example project is available here