Kahibaro
Discord Login Register

18.1 HTTP Basics

Understanding HTTP in Android Apps

In modern Android apps, almost all online features depend on HTTP. Whenever your app talks to a server, loads data from an API, or sends user information to the cloud, it is very likely using HTTP behind the scenes. In this chapter you will learn what HTTP is, how it is structured, and how requests and responses work, so that later you can use libraries like Retrofit with confidence.

What HTTP Is and Why It Matters

HTTP stands for HyperText Transfer Protocol. It is a set of rules that defines how clients and servers communicate on the web. In this model, your Android app is the client. It sends HTTP requests to a server, and the server responds with HTTP responses.

HTTP is a text based protocol. Both the request and the response are made of plain text lines that follow a standard structure. Libraries hide most of that from you, but understanding the structure helps you debug problems, read server logs, and design how your app should communicate with backends.

HTTP used today is mostly HTTP/1.1 and HTTP/2, but the essential ideas in this chapter apply to all versions.

Client, Server, and URLs

Every HTTP call has two roles. The client starts the communication and sends the request. The server listens for requests and sends back responses. Your Android app always acts as the client when it talks to a web API.

To tell the client where to send a request, you use a URL. A full URL has several parts, for example:

https://api.example.com/users/42?include=posts

Here, https is the protocol. This is HTTP over TLS, which means the connection is encrypted. api.example.com is the host name, which points to a server on the internet. The part /users/42 is the path, which identifies a resource. The query string ?include=posts adds extra parameters. Each piece influences where the request goes and what data it asks for.

For Android development, you usually configure a base URL such as https://api.example.com/ and then append paths like users or posts for specific endpoints.

HTTP Methods and Their Intent

HTTP defines methods that tell the server what you intend to do with a resource. The most common ones you will see in Android apps are GET, POST, PUT, PATCH, and DELETE.

A GET request asks the server to send data. It does not modify anything. When your app loads a list of products or user details, it usually uses GET. For example, requesting GET /products from https://shop.example.com asks the server to return a list of products.

A POST request sends new data to the server. It is often used to create resources. For example, when a user signs up, your app might send POST /users with a JSON body that contains their name and email. The server then stores this and returns information about the new user.

PUT is typically used to completely replace an existing resource with new data. If your app allows editing a profile, a PUT /users/42 request might send a full JSON object for user 42, and the server replaces the old data with the new one.

PATCH updates part of an existing resource. Instead of sending the full object, a PATCH /users/42 might only include the fields that changed, for example just the new email.

DELETE asks the server to remove a resource. For instance, DELETE /posts/99 tells the server to delete the post with id 99.

A GET request should not change server data. Treat GET as a safe and read only method, and never use it for actions that modify or delete information.

Structure of an HTTP Request

Every HTTP request has three main parts. These are the request line, the headers, and an optional body.

The request line is the first line and contains the method, the path, and the HTTP version. An example looks like this:

GET /users/42 HTTP/1.1

This means the client is using the GET method, requesting /users/42 from the server, and using version HTTP/1.1.

Headers come after the request line. Each header is on its own line and uses the format Name: value. Headers provide additional information, such as what host you want, what content types you can handle, and how to authenticate. For example:

Host: api.example.com
Accept: application/json
Authorization: Bearer <token>

The body is optional and follows a blank line after the headers. Methods like GET normally have no body, while POST and PUT often include a body that holds data to send to the server. When you send JSON, the body could look like this:

{"name": "Alice", "email": "alice@example.com"}

In Android, you rarely build raw HTTP requests by hand, but every library you use eventually turns your code into exactly this structure.

Structure of an HTTP Response

The server reply also has three main parts. These are the status line, the headers, and an optional body.

The status line is the first line of the response, for example:

HTTP/1.1 200 OK

This tells you the HTTP version, a numeric status code, and a short reason phrase. The status code is extremely important when you handle responses in your app.

Response headers follow in the same Name: value format. Examples include:

Content-Type: application/json
Content-Length: 123
Cache-Control: no-cache

These headers tell your app how to interpret the body and how to handle caching and other behavior.

The response body is the actual data returned by the server. For web APIs used by Android apps, this body is often JSON text. For example:

{"id":42,"name":"Alice","email":"alice@example.com"}

Your networking code receives this text, then your JSON parsing code turns it into Kotlin objects that you can use in the app.

HTTP Status Codes and Their Meaning

Status codes are three digit numbers in the response status line. They tell your app whether a request succeeded, failed, or needs more action. They are grouped by the first digit.

1xx codes are informational and you usually do not work with them directly in Android apps.

2xx codes indicate success. The most common is 200 OK which means the request succeeded and the server is returning data. 201 Created is common for POST requests that create a resource. It means the resource was successfully created.

3xx codes represent redirection. For example, 301 Moved Permanently or 302 Found tell the client that the resource is at a different URL. In practice, HTTP client libraries handle many redirects automatically.

4xx codes tell you there was a client error. 400 Bad Request means the server could not understand your request. 401 Unauthorized typically means you are not authenticated or your token is missing. 403 Forbidden means you are authenticated but not allowed to access that resource. 404 Not Found means the resource does not exist at the given path.

5xx codes indicate server errors. 500 Internal Server Error is a generic error when something failed on the server side. 503 Service Unavailable means the server is temporarily unable to handle the request, for example during maintenance.

Your app should always check the HTTP status code before trusting the response body. Treat any non 2xx code as a failure and handle it accordingly in your UI and logic.

Headers and Content Types

HTTP headers are key to telling the server and the client how to handle data. Some headers are especially important for Android apps.

Content-Type describes the media type of the body. For JSON APIs, it is usually application/json. When your app sends JSON data in a POST request, it must set this header so the server knows how to parse the body.

Accept tells the server what content types your client can handle. For a JSON based app, a common value is Accept: application/json. This shows that you expect JSON responses.

Authorization carries credentials. Many APIs use tokens, often in the form Authorization: Bearer <token>. Your app includes this header in every request after the user logs in.

There are many other headers for caching, compression, and language preferences. You do not need all of them as a beginner, but you should recognize that they are part of the HTTP protocol and can affect how your app behaves.

HTTPS and Basic Security

HTTP on its own is not encrypted. Anyone who can listen to the network can see the content of requests, including usernames and passwords. To protect data in transit, modern apps use HTTPS.

HTTPS means HTTP over TLS, which adds encryption between the client and the server. In practice you use a URL that starts with https:// instead of http://. The HTTP protocol itself stays the same. The request line, headers, and body still exist, but they are transmitted in an encrypted form on the network.

In Android, you almost always use HTTPS for real user data. Your networking libraries and the system handle the encryption details automatically when you use https URLs.

Never send sensitive information such as passwords or tokens over plain http://. Always use https:// to keep data encrypted between your app and the server.

HTTP and REST Style APIs

Many APIs that Android apps use are designed in a REST style. In this approach, you treat different things as resources and you access them using paths and HTTP methods.

For example, /users might be the collection of users, and /users/42 a single user. You use GET /users to list users, GET /users/42 to get details about one user, POST /users to create a new user, PUT /users/42 to replace user 42, and DELETE /users/42 to remove that user.

The important part is that REST uses the existing features of HTTP instead of inventing new rules. When you later work with Retrofit, you will map Kotlin functions to specific HTTP methods and paths that follow this style.

A Simple HTTP Example End to End

To connect everything, imagine your app needs to fetch a list of posts from https://api.example.com/posts. Your code triggers a GET request to that URL. Internally, the library builds something like:

GET /posts HTTP/1.1
Host: api.example.com
Accept: application/json

The server receives this request, finds the posts resource, and sends back:

HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 157

[{"id":1,"title":"First post"},{"id":2,"title":"Second post"}]

Your HTTP client code reads the status code 200, sees that the request was successful, checks the Content-Type, then passes the JSON body to your JSON parser. The parser converts it into a list of Kotlin objects, which you display in a RecyclerView.

Throughout this process, you never see the raw HTTP text, but everything you do is based on these HTTP rules. As you move on to REST APIs and libraries such as Retrofit, this understanding of HTTP basics will help you make sense of how network calls work in your Android apps.

Views: 2

Comments

Please login to add a comment.

Don't have an account? Register now!