0% found this document useful (0 votes)
15 views18 pages

HTTP

Chapter 11 covers networking in Android Studio, detailing essential permissions, network requests using libraries such as Volley and Retrofit, and handling asynchronous operations. It provides examples for consuming web services, downloading binary and text content, and accessing JSON services with Retrofit. The chapter emphasizes the importance of error handling, security measures, and the use of modern approaches like Kotlin Coroutines for efficient network operations.

Uploaded by

INDHU MATHI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views18 pages

HTTP

Chapter 11 covers networking in Android Studio, detailing essential permissions, network requests using libraries such as Volley and Retrofit, and handling asynchronous operations. It provides examples for consuming web services, downloading binary and text content, and accessing JSON services with Retrofit. The chapter emphasizes the importance of error handling, security measures, and the use of modern approaches like Kotlin Coroutines for efficient network operations.

Uploaded by

INDHU MATHI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

CHAPTER 11: NETWORKING

Networking in Android Studio involves various techniques and APIs to communicate with
remote servers, fetch data, and perform network operations. Here are some key aspects
and steps you might encounter:

1. Permissions: Ensure that your app has the necessary permissions declared in the manifest
file to access the network. Common permissions include `INTERNET` and
`ACCESS_NETWORK_STATE`.

```xml

<uses-permission android:name="android.permission.INTERNET" />

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

```

2. Network Requests:

- HTTP Requests: Android provides classes like `HttpURLConnection` and `HttpClient`


(deprecated in newer Android versions) to make HTTP requests.

- Volley Library: Google's Volley library offers a higher-level API for handling network
operations. It supports request queuing, prioritization, caching, and more.

- Retrofit Library: A popular choice for RESTful API communication, Retrofit simplifies
network requests by defining an interface with annotations for API endpoints.

3. Asynchronous Operations:

- Network operations should be performed asynchronously to avoid blocking the UI


thread. This can be achieved using threads, AsyncTask (for simpler cases), or modern
alternatives like Kotlin Coroutines or RxJava.

4. JSON Parsing: When dealing with APIs that return JSON data (common in RESTful
services), you'll need to parse the JSON response into usable objects. Android provides
classes like `JSONObject` and `JSONArray` for JSON parsing, but libraries like Gson or Jackson
offer more convenient solutions.

5. Handling Responses:

- Implement callbacks or listeners to handle the responses from network requests. For
example, in Volley, you'd create a `Response.Listener` to handle successful responses and a
`Response.ErrorListener` for error cases.

- Retrofit uses interfaces with annotated methods to define callback functions for different
response types.

6. Error Handling and Connectivity:

- Implement mechanisms to handle network errors, such as timeouts, connectivity issues,


and server errors. Android's `ConnectivityManager` can be used to check network
connectivity status dynamically.

7. Security:

- When dealing with sensitive data or secure APIs, ensure proper security measures such
as HTTPS communication and data encryption where necessary.

CONSUMING WEB SERVICES USING HTTP


To consume web services using HTTP in Android Studio, you can use classes like
`HttpURLConnection` or third-party libraries like OkHttp. Here's a basic example using
`HttpURLConnection` to make a GET request to a web service:

1. Add Permissions: Make sure to add the necessary permissions in your


AndroidManifest.xml file.

```xml

<uses-permission android:name="android.permission.INTERNET" />

```
2. AsyncTask for Network Operations (or use Kotlin Coroutines or RxJava for more modern
approaches):

```java

import android.os.AsyncTask;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

public class WebServiceTask extends AsyncTask<Void, Void, String> {

private static final String WEB_SERVICE_URL = "https://api.example.com/data"; // Your


web service URL

@Override

protected String doInBackground(Void... voids) {

HttpURLConnection urlConnection = null;

BufferedReader reader = null;

String result = null;

try {

URL url = new URL(WEB_SERVICE_URL);

urlConnection = (HttpURLConnection) url.openConnection();

urlConnection.setRequestMethod("GET");

InputStream inputStream = urlConnection.getInputStream();

StringBuilder buffer = new StringBuilder();


if (inputStream == null) {

// Stream was empty

return null;

reader = new BufferedReader(new InputStreamReader(inputStream));

String line;

while ((line = reader.readLine()) != null) {

buffer.append(line).append("\n");

if (buffer.length() == 0) {

// Stream was empty

return null;

result = buffer.toString();

} catch (IOException e) {

e.printStackTrace();

} finally {

if (urlConnection != null) {

urlConnection.disconnect();

if (reader != null) {

try {

reader.close();

} catch (IOException e) {

e.printStackTrace();

}
}

return result;

@Override

protected void onPostExecute(String result) {

super.onPostExecute(result);

// Handle the result here (e.g., update UI, parse JSON, etc.)

if (result != null) {

// Process the result

} else {

// Handle error or empty response

```

3. Execute the AsyncTask from your activity or fragment:

```java

new WebServiceTask().execute();

```

This example demonstrates a simple HTTP GET request. For more complex operations, such
as POST requests, handling JSON responses, or managing headers, you'll need to extend this
code accordingly. Keep in mind that for production apps, consider using libraries like Retrofit
or OkHttp, as they provide more features and handle many aspects of networking more
efficiently.
DOWNLOADING BINARY DATA
Downloading binary data in Android typically involves using HTTP to retrieve files such as
images, videos, PDFs, etc. Here's a basic example of how you can download binary data
(e.g., an image) using `HttpURLConnection` in Android:

1. Add Permissions: Ensure that you have the necessary permissions in your
AndroidManifest.xml file

```xml

<uses-permission android:name="android.permission.INTERNET" />

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

```

2. AsyncTask for Downloading (or use Kotlin Coroutines or RxJava for more modern
approaches):

```java

import android.os.AsyncTask;

import android.os.Environment;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.URL;

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

private static final String DOWNLOAD_PATH =


Environment.getExternalStorageDirectory().getPath(); // Download directory

@Override

protected Void doInBackground(String... params) {

String fileUrl = params[0]; // URL of the file to download

String fileName = params[1]; // Name of the downloaded file


try {

URL url = new URL(fileUrl);

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

connection.connect();

int responseCode = connection.getResponseCode();

if (responseCode == HttpURLConnection.HTTP_OK) {

InputStream inputStream = connection.getInputStream();

FileOutputStream outputStream = new FileOutputStream(DOWNLOAD_PATH +


"/" + fileName);

byte[] buffer = new byte[1024];

int bytesRead;

while ((bytesRead = inputStream.read(buffer)) != -1) {

outputStream.write(buffer, 0, bytesRead);

outputStream.close();

inputStream.close();

connection.disconnect();

} catch (Exception e) {

e.printStackTrace();

return null;

@Override

protected void onPostExecute(Void result) {


super.onPostExecute(result);

// Download completed, handle any post-download tasks here

```

3. Execute the DownloadTask from your activity or fragment:

```java

String fileUrl = "https://example.com/image.jpg"; // URL of the file to download

String fileName = "image.jpg"; // Name of the downloaded file

new DownloadTask().execute(fileUrl, fileName);

```

In this example, the `DownloadTask` AsyncTask downloads a binary file (e.g., an image) from
the specified URL and saves it to the device's external storage directory. You can customize
the download path and file name as needed.

Remember to handle permissions, especially WRITE_EXTERNAL_STORAGE, and consider


using more advanced libraries like OkHttp or Retrofit for complex download scenarios with
features like progress tracking and error handling.

DOWNLOADING TEXT CONTENT


Downloading text content in Android is similar to downloading binary data, but you handle
the response as text instead of binary. Here's an example using `HttpURLConnection` to
download and read text content from a URL:

1. Add Permissions: Make sure you have the necessary permissions in your
AndroidManifest.xml file.
```xml

<uses-permission android:name="android.permission.INTERNET" />

```

2. AsyncTask for Downloading (or use Kotlin Coroutines or RxJava for more modern
approaches):

```java

import android.os.AsyncTask;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

public class DownloadTextTask extends AsyncTask<String, Void, String> {

@Override

protected String doInBackground(String... urls) {

String urlString = urls[0]; // URL of the text content

StringBuilder result = new StringBuilder();

HttpURLConnection urlConnection = null;

BufferedReader reader = null;

try {

URL url = new URL(urlString);

urlConnection = (HttpURLConnection) url.openConnection();


urlConnection.connect();

InputStream inputStream = urlConnection.getInputStream();

if (inputStream == null) {

// Handle empty response

return null;

reader = new BufferedReader(new InputStreamReader(inputStream));

String line;

while ((line = reader.readLine()) != null) {

result.append(line);

} catch (IOException e) {

e.printStackTrace();

} finally {

if (urlConnection != null) {

urlConnection.disconnect();

if (reader != null) {

try {

reader.close();

} catch (IOException e) {

e.printStackTrace();

return result.toString();
}

@Override

protected void onPostExecute(String result) {

super.onPostExecute(result);

// Handle the downloaded text content here

if (result != null) {

// Process the text content

} else {

// Handle error or empty response

```

3. Execute the DownloadTextTask from your activity or fragment:

```java

String url = "https://example.com/textfile.txt"; // URL of the text content

new DownloadTextTask().execute(url);

```

In this example, the `DownloadTextTask` AsyncTask downloads text content from the
specified URL and returns it as a String. You can then process this text content in the
`onPostExecute` method, such as displaying it in a TextView or performing further
operations on it.

For more advanced networking tasks or handling JSON responses, consider using libraries
like OkHttp or Retrofit, as they provide more features and simplify the networking code.
ACCESSING WEB SERVICES USING THE GET METHOD
Accessing web services using the GET method in Android involves making HTTP GET
requests to a server to fetch data. You can use classes like `HttpURLConnection`, OkHttp, or
Retrofit to handle GET requests efficiently. Here's an example using `HttpURLConnection`:

1. Add Permissions: Make sure to add the necessary permissions in your


AndroidManifest.xml file.

```xml

<uses-permission android:name="android.permission.INTERNET" />

```

2. AsyncTask for GET Request (or use Kotlin Coroutines or RxJava for modern approaches):

```java

import android.os.AsyncTask;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

public class GetRequestTask extends AsyncTask<String, Void, String> {

@Override

protected String doInBackground(String... urls) {

String urlString = urls[0]; // URL of the web service

HttpURLConnection urlConnection = null;

BufferedReader reader = null;


StringBuilder result = new StringBuilder();

try {

URL url = new URL(urlString);

urlConnection = (HttpURLConnection) url.openConnection();

urlConnection.setRequestMethod("GET");

InputStream inputStream = urlConnection.getInputStream();

if (inputStream == null) {

// Handle empty response

return null;

reader = new BufferedReader(new InputStreamReader(inputStream));

String line;

while ((line = reader.readLine()) != null) {

result.append(line);

} catch (IOException e) {

e.printStackTrace();

} finally {

if (urlConnection != null) {

urlConnection.disconnect();

if (reader != null) {

try {

reader.close();

} catch (IOException e) {

e.printStackTrace();
}

return result.toString();

@Override

protected void onPostExecute(String result) {

super.onPostExecute(result);

// Handle the GET request response here

if (result != null) {

// Process the response data

} else {

// Handle error or empty response

```

3. Execute the GetRequestTask from your activity or fragment:

```java

String url = "https://api.example.com/data"; // URL of the web service

new GetRequestTask().execute(url);

```

In this example, the `GetRequestTask` AsyncTask sends a GET request to the specified URL
and retrieves the response data as a String. You can customize the URL and handle the
response in the `onPostExecute` method, such as parsing JSON data or updating UI
components with the fetched data.
For more advanced features and better handling of network operations, consider using
libraries like OkHttp or Retrofit, as they offer additional functionalities such as automatic
JSON parsing, request queuing, caching, and more.

CONSUMING JSON SERVICES


Consuming JSON services in Android typically involves making HTTP requests to an API that
returns data in JSON format and then parsing that JSON data to use it in your app. Here's a
step-by-step guide using Retrofit, a popular library for working with RESTful APIs and JSON
data in Android:

1. Add Dependencies: Add Retrofit and Gson (for JSON parsing) dependencies to your app's
build.gradle file.

```groovy

implementation 'com.squareup.retrofit2:retrofit:2.9.0'

implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

```

2. Create a Model Class: Define a POJO (Plain Old Java Object) class to represent the JSON
data you expect to receive. For example, if your JSON response contains information about
users, you might create a `User` class like this:

```java

public class User {

private int id;

private String name;

private String email;

// Getters and setters

```
3. Create an Interface for API Calls: Define an interface that describes the API endpoints and
their expected responses. Annotate the interface methods with Retrofit annotations like
`@GET`, `@POST`, etc., and specify the endpoint path.

```java

import retrofit2.Call;

import retrofit2.http.GET;

public interface ApiService {

@GET("users") // Example endpoint, replace with your actual endpoint

Call<List<User>> getUsers();

```

4. Create Retrofit Instance: Create a Retrofit instance and configure it with your base URL
and the converter factory for Gson.

```java

import retrofit2.Retrofit;

import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitClient {

private static Retrofit retrofit;

private static final String BASE_URL = "https://api.example.com/";

public static Retrofit getClient() {

if (retrofit == null) {

retrofit = new Retrofit.Builder()

.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())

.build();

return retrofit;

```

5. Perform API Call: Use the Retrofit instance and the ApiService interface to make API calls
from your activity or fragment.

```java

import retrofit2.Call;

import retrofit2.Callback;

import retrofit2.Response;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

ApiService apiService = RetrofitClient.getClient().create(ApiService.class);

Call<List<User>> call = apiService.getUsers();


call.enqueue(new Callback<List<User>>() {

@Override

public void onResponse(Call<List<User>> call, Response<List<User>> response) {

if (response.isSuccessful() && response.body() != null) {

List<User> userList = response.body();

// Process the user list here

} else {

// Handle error response

@Override

public void onFailure(Call<List<User>> call, Throwable t) {

// Handle network errors or API call failure

});

```

In this example, Retrofit handles the network operations and JSON parsing for you. When
you make the API call using Retrofit's `enqueue` method, it automatically sends the request
in the background thread and provides the response in the callback methods (`onResponse`
and `onFailure`) on the main thread.

Make sure to replace the placeholder URLs, endpoint paths, and JSON parsing logic with
your actual API details and data models.

You might also like