Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

HTTP Requests with HttpURLConnection

Introduction

In this tutorial, we will learn how to perform HTTP requests using the HttpURLConnection class in Android. HttpURLConnection is a class in the java.net package that allows us to send and receive data over the web using the HTTP protocol. This tutorial will cover everything from setting up the connection to handling the response.

Setting Up the HttpURLConnection

Before we can send an HTTP request, we need to set up the HttpURLConnection. This involves creating a URL object and opening a connection to that URL.

URL url = new URL("http://www.example.com");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

Configuring the Connection

Once we have opened the connection, we need to configure it. This includes setting the request method (GET, POST, etc.), setting timeouts, and adding request headers.

urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(15000);
urlConnection.setReadTimeout(15000);
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0");

Sending the Request

After configuring the connection, we can send the request. For a GET request, this simply involves calling the connect method. For a POST request, we need to write the request body to the output stream.

// For GET request
urlConnection.connect();

// For POST request
urlConnection.setDoOutput(true);
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write("param1=value1¶m2=value2");
writer.flush();
writer.close();
os.close();

Handling the Response

Once the request has been sent, we need to handle the response. This involves reading the response code and the response body.

int responseCode = urlConnection.getResponseCode();

if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();

// Print the response
System.out.println(response.toString());
} else {
System.out.println("GET request failed");
}

Example: Complete GET Request

Here is a complete example of a GET request using HttpURLConnection.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class GetRequestExample {
public static void main(String[] args) {
try {
URL url = new URL("http://www.example.com");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(15000);
urlConnection.setReadTimeout(15000);
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0");

int responseCode = urlConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();

System.out.println(response.toString());
} else {
System.out.println("GET request failed");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Example: Complete POST Request

Here is a complete example of a POST request using HttpURLConnection.

import java.io.BufferedWriter;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class PostRequestExample {
public static void main(String[] args) {
try {
URL url = new URL("http://www.example.com");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setConnectTimeout(15000);
urlConnection.setReadTimeout(15000);
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0");
urlConnection.setDoOutput(true);

OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write("param1=value1¶m2=value2");
writer.flush();
writer.close();
os.close();

int responseCode = urlConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();

System.out.println(response.toString());
} else {
System.out.println("POST request failed");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Conclusion

In this tutorial, we covered how to make HTTP requests using the HttpURLConnection class in Android. We learned how to set up the connection, configure it, send GET and POST requests, and handle the responses. With this knowledge, you can now integrate HTTP requests into your Android applications.