0% found this document useful (0 votes)
10 views19 pages

MC 9 8A Shubham

mobile computing

Uploaded by

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

MC 9 8A Shubham

mobile computing

Uploaded by

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

Name of Student : Shubham Chougule

Roll No : 8 LAB Assignment Number : 9

Title of LAB Assignment :


Android program based on Rest API.
A) Create a basic application that allows you to download HTML from a given
web page using HttpURLConnection.
B) Create an application to parse the data using JSON Object methods and set it
in the Text View’s. (Employee name and salary stored in JSON format).

DOP : 11/10/2024 DOS: 25/10/2024

CO MAPPED : PO MAPPED: FACULTY MARKS:

CO2, CO5 PO2, PO3, SIGNATURE:

PO5, PSO1,

PS02
Practical No: 9
AIM: ANDROID PROGRAM BASED ON REST API.
A) CREATE A BASIC APPLICATION THAT ALLOWS YOU TO
DOWNLOAD HTML FROM A GIVEN WEB PAGE USING
HTTPURLCONNECTION.
B) CREATE AN APPLICATION TO PARSE THE DATA USING JSON OBJECT
METHODS AND SET IT IN THE TEXT VIEW’S. (EMPLOYEE NAME AND SALARY
STORED IN JSON FORMAT).

THEORY:

1. What is REST?

REST (Representational State Transfer) is an architectural style developed by Roy Fielding in


2000. REST leverages standard web protocols and HTTP methods to create, retrieve, update, or
delete resources. RESTful systems are designed to be stateless and cacheable, and they focus on
scalability, simplicity, and uniformity.

Key Characteristics of REST:

● Stateless: Each request from a client to the server must contain all the information
needed to process the request. The server does not store the client’s state between
requests.
● Client-Server Architecture: There is a clear separation between the client (frontend)
and server (backend). The client requests resources, and the server responds with the
necessary data.
● Uniform Interface: REST defines a uniform interface for interacting with resources.
This is typically based on HTTP and uses standard methods like GET, POST, PUT,
DELETE, and PATCH.
● Resource-based: In REST, everything is considered a resource, and these resources
are identified using URIs (Uniform Resource Identifiers).
● Representation: Resources are usually represented in formats like JSON, XML, or
HTML. JSON is the most commonly used format because of its lightweight nature.

2. REST API Principles

To adhere to REST principles, APIs should follow the following constraints:


● Client-Server: The client and server operate independently, and the API allows for
easy interaction between them. The server does not need to know the client state, and
the client does not store server state.
● Statelessness: Every API call must contain all the necessary information for
processing. No session state is stored on the server. Each request from the client should
contain everything required to perform the operation (authentication, data, etc.).
● Cacheability: Responses from the server should define whether they can be cached by
the client to improve performance. This reduces the need to repeatedly send the same
data.
● Uniform Interface: The API should provide a consistent and standardized interface.
This involves:
○ Resource Identification: Resources are identified by URIs.
○ Manipulation of Resources: The representation of resources is
modifiable, typically via HTTP methods.
○ Self-descriptive Messages: Each message contains enough information to
describe how to process the message.
○ Hypermedia as the Engine of Application State (HATEOAS): Hypermedia
links in responses allow the client to navigate the API dynamically.
● Layered System: The API architecture may have multiple layers, such as
security, caching, load balancing, etc. Each layer is abstracted, allowing for
scalability and flexibility.

3. HTTP Methods in REST API

REST APIs utilize standard HTTP methods to interact with resources:

● GET: Used to retrieve a resource. It’s a read-only operation and should not have
side effects.
○ Example: GET /users retrieves a list of users.
● POST: Used to create a new resource on the server. It often involves sending data to the
server (e.g., via JSON).
○ Example: POST /users creates a new user.
● PUT: Used to update or replace an existing resource. The entire resource is sent to
update it.
○ Example: PUT /users/1 updates the details of user with ID 1.
● PATCH: Used to partially update a resource. Unlike PUT, only the fields that need to
be updated are sent.
○ Example: PATCH /users/1 updates part of user 1’s information.
● DELETE: Used to delete a resource.
○ Example: DELETE /users/1 deletes user 1.

4. Resource Representation

A resource in REST is typically represented using a common format such as JSON, XML, or
HTML. JSON (JavaScript Object Notation) is the most popular format due to its simplicity,
readability, and ease of use in web applications.

Example of a JSON resource representing a user:

{
"id": 1,
"name": "John Doe",
"email": "[email protected]"
}

The server responds to client requests by providing these representations in a standardized format,
enabling the client to understand and process the data.

5. RESTful URL Design

In REST API design, resources are identified by URIs (Uniform Resource Identifiers), and
these URIs are structured based on a logical hierarchy. RESTful URLs should be intuitive,
descriptive, and use nouns rather than verbs.

Examples of RESTful URL patterns:

● GET /users: Retrieves a list of users.


● GET /users/1: Retrieves the details of a specific user by ID.
● POST /users: Creates a new user.
● PUT /users/1: Updates the information for user ID 1.
● DELETE /users/1: Deletes user ID 1.

6. Advantages of REST APIs

● Scalability: The stateless nature of REST makes it easy to scale web services.
● Simplicity: REST APIs leverage standard HTTP methods and are easy to understand
and implement.
● Flexibility: REST can return data in different formats (e.g., JSON, XML), making it
suitable for a wide variety of applications (web, mobile, etc.).
● Separation of Client and Server: REST APIs provide a clear separation between the
client and server, allowing independent development on both sides.

A) CREATE A BASIC APPLICATION THAT ALLOWS YOU TO


DOWNLOAD HTML FROM A GIVEN WEB PAGE USING
HTTPURLCONNECTION.

CODE:

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

Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
android:id="@+id/main">

<TextView
android:layout_width="match_p
arent"
android:layout_height="wrap_co
ntent" android:text="HTML
Fetcher"
android:textAlignment="center"
android:textSize="40dp"
android:fontFamily="serif-mono
space" android:textStyle="bold"
android:layout_margin="30dp"/
>

<EditText
android:id="@+id/urlInput
"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter URL"
android:inputType="textUri"
android:textSize="20dp"
android:layout_marginBottom="20dp"/>
<Button
android:id="@+id/fetchButt
on"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fetch HTML"
android:textSize="23dp"
android:layout_gravity="center_horizont
al"
android:layout_marginBottom="20dp"/>

<ScrollView
android:layout_width="match_p
arent"
android:layout_height="wrap_co
ntent"
android:fillViewport="true">

<TextView
android:id="@+id/htmlOutput"
android:layout_width="match_p
arent"
android:layout_height="wrap_co
ntent"
android:paddingTop="10dp"
android:textSize="14sp" />

</ScrollView>

</LinearLayout
>

MainActivity.java
package com.example.mcpractical9;
import
androidx.appcompat.app.AppCompatActivit
y; import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import
android.widget.Button;
import
android.widget.EditText;
import
android.widget.TextView;
import java.io.BufferedReader;
import
java.io.InputStreamReader;
import
java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {


private EditText urlInput;
private TextView
htmlOutput;

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

urlInput = findViewById(R.id.urlInput);
htmlOutput =
findViewById(R.id.htmlOutput);
Button fetchButton = findViewById(R.id.fetchButton);

fetchButton.setOnClickListener(new
View.OnClickListener() { @Override
public void onClick(View v) {
String urlString =
urlInput.getText().toString(); new
FetchHtmlTask().execute(urlString);
}
});
}

private class FetchHtmlTask extends AsyncTask<String, Void,


String> { @Override
protected String doInBackground(String...
urls) { String htmlContent = "";
try {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();

BufferedReader reader = new BufferedReader(new


InputStreamReader(connection.getInputStream()));
StringBuilder builder = new
StringBuilder(); String line;
while ((line = reader.readLine()) != null) {
builder.append(line).append("\n");
}
htmlContent =
builder.toString();
reader.close();
} catch (Exception e) {
htmlContent = "Error: " + e.getMessage();
}
return htmlContent;
}

@Override
protected void onPostExecute(String
result) { htmlOutput.setText(result);
}
}
}

OUTPUT:
B) CREATE AN APPLICATION TO PARSE THE DATA USING JSON OBJECT
METHODS AND SET IT IN THE TEXT VIEW’S. (EMPLOYEE NAME AND SALARY
STORED IN JSON FORMAT).

CODE:
Activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
android:id="@+id/main">

<TextView
android:layout_width="match_p
arent"
android:layout_height="wrap_co
ntent" android:text="JSON
Parser"
android:textAlignment="center"
android:textSize="40dp"
android:fontFamily="serif-mono
space" android:textStyle="bold"
android:layout_margin="30dp"/
>

<TextView
android:id="@+id/jsonStringVie
w"
android:layout_width="wrap_co
ntent"
android:layout_height="wrap_co
ntent" android:text="JSON
String: "
android:paddingBottom="10dp"
android:textSize="20dp" />
<Button
android:id="@+id/parseBut
ton"
android:layout_width="match_parent"
android:layout_height="wrap_co
ntent" android:text="Parse
JSON"
android:textSize="23dp"/>

<TextView
android:id="@+id/employeeName"
android:layout_width="wrap_conte
nt"
android:layout_height="wrap_conte
nt" android:text="Employee Name:
" android:paddingTop="20dp"
android:textSize="23dp"
android:layout_marginBottom="20
dp"/>

<TextView
android:id="@+id/employeeSala
ry"
android:layout_width="wrap_co
ntent"
android:layout_height="wrap_co
ntent" android:text="Employee
Salary: "
android:textSize="23dp"/>
</LinearLayout>

MainActivity.java

package com.example.mcpractical9;

import
androidx.appcompat.app.AppCompatActivit
y; import android.os.Bundle;
import android.view.View;
import
android.widget.Button;
import
android.widget.TextView;
import
org.json.JSONException;
import
org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
private TextView employeeName, employeeSalary,
jsonStringView; @Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

employeeName = findViewById(R.id.employeeName);
employeeSalary =
findViewById(R.id.employeeSalary);
jsonStringView =
findViewById(R.id.jsonStringView); Button
parseButton =
findViewById(R.id.parseButton);

// Example JSON string


String jsonString = "{\n" +
" \"employee\": {\n" +
" \"name\": \"Heetika
Vaity\",\n" + " \"salary\":
50000\n" +
" }\n" +
"}";

// Display the raw JSON string in the TextView


jsonStringView.setText("JSON String:\n" + jsonString);

// Parse the JSON when the button is clicked


parseButton.setOnClickListener(new
View.OnClickListener() { @Override
public void onClick(View v) {
parseJson(jsonString);
}
});
}

private void parseJson(String


jsonString) { try {
// Create JSONObject from the JSON string
JSONObject jsonObject = new JSONObject(jsonString);

// Get the employee object from the JSON


JSONObject employeeObject = jsonObject.getJSONObject("employee");

// Extract name and salary from the employee


object String name =
employeeObject.getString("name"); int
salary = employeeObject.getInt("salary");

// Set the extracted data to the TextViews


employeeName.setText("Employee Name: " +
name); employeeSalary.setText("Employee
Salary: $" + salary);

} catch (JSONException e) {
e.printStackTrace();
employeeName.setText("Error parsing JSON");
employeeSalary.setText("");
}
}
}

OUTPUT:
CONCLUSION:

REST APIs are a standard way to build scalable, flexible, and lightweight services. They allow
different systems and platforms to communicate via HTTP, using common methods such as GET,
POST, PUT, and DELETE. With the rise of web, mobile, and cloud applications, REST APIs have
become a vital tool for enabling seamless and efficient communication between clients and
servers.

You might also like