How to Call Rest API from an Android App

How do I call REST API from an android app?

  1. If you want to integrate Retrofit (all steps defined here):

Goto my blog : retrofit with kotlin


  1. Please use android-async-http library.

the link below explains everything step by step.

http://loopj.com/android-async-http/

Here are sample apps:

  1. http://www.techrepublic.com/blog/software-engineer/calling-restful-services-from-your-android-app/

  2. http://blog.strikeiron.com/bid/73189/Integrate-a-REST-API-into-Android-Application-in-less-than-15-minutes

Create a class :

public class HttpUtils {
private static final String BASE_URL = "http://api.twitter.com/1/";

private static AsyncHttpClient client = new AsyncHttpClient();

public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(getAbsoluteUrl(url), params, responseHandler);
}

public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
}

public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(url, params, responseHandler);
}

public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(url, params, responseHandler);
}

private static String getAbsoluteUrl(String relativeUrl) {
return BASE_URL + relativeUrl;
}
}

Call Method :

    RequestParams rp = new RequestParams();
rp.add("username", "aaa"); rp.add("password", "aaa@123");

HttpUtils.post(AppConstant.URL_FEED, rp, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// If the response is JSONObject instead of expected JSONArray
Log.d("asd", "---------------- this is response : " + response);
try {
JSONObject serverResp = new JSONObject(response.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
// Pull out the first event on the public timeline

}
});

Please grant internet permission in your manifest file.

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

you can add compile 'com.loopj.android:android-async-http:1.4.9' for Header[] and compile 'org.json:json:20160212' for JSONObject in build.gradle file if required.

Consuming a restful API from Android app

Yes , you need to do API call to talk to your restful server . For this you can use any below implementation .

Sending Request

Retrofit

Retrofit Example

Async Client Example

How to consume REST API key in my android app?

For the quota management, it's the backend logic and it handles user requests so you should follow the backend way in scenario 1. Here is how it should work.

  1. Device Login. On success, the server returns an access token as a response. Store token in device safe place(i.e. SharedPreferences in android).
  2. Send the token in Authorization header of every request to the server, Your server should be guarded by Authorization. Server updates the quota consumed for the day. Here is how the server can manage quota,

    ‣ Identify user based on the token in Authorization header and update the quota.
    ‣ If quota exceeds, return some meaningful error to the device.

For scenario 2, make the token User Independent (multiple device logins allowed for the same account). By making the token User Independent and above given flow, you can achieve aspects given in your question. let me know if you have a question.

I suggest using JWT Token. as it's a standard JSON web token and globally used. it has several benefits and availability on major platforms.

how to secure an API when called by Android app

AUTH TOKENS

If I have a token for auth.

Please bear in mind that a User Auth token only identifies who is in the request, not what is doing the request. Don't worry if you were not aware of this yet, because its a very usual misconception among developers of any level and background.

So lets' clear it up first...

The Difference Between WHO and WHAT is Accessing the API Server

I wrote a series of articles around API and Mobile security, and in the article Why Does Your Mobile App Need An Api Key? you can read in more detail the difference between who and what is accessing your API server, but I will quote some of the main points from it:

The what is the thing making the request to the API server. Is it really a genuine instance of your mobile app, or is it a bot, an automated script or an attacker manually poking around your API server with a tool like Postman?

The who is the user of the mobile app that we can authenticate, authorize and identify in several ways, like using OpenID Connect or OAUTH2 flows.

So think about the who as the user your API server will be able to Authenticate and Authorize access to the data, and think about the what as the software making that request in behalf of the user.

EVERYTHING IN THE CLIENT CAN BE CAPTURED OR EXTRACTED

If I have a token for auth. then app's users can easily capture the POST request and find the token, even if I hash the token within the app and send it to server, then compare it to the hashed token from DB users still can capture the hashed token...

No matter what technique you use in the end an attacker can always get hold on any secret you try hard to hide from him, the question is more how much effort he is willing to put in getting it from your mobile app and/or how much knowledge he have to perform such tasks.

Nowadays we have a plethora of tools to help security researchers or anyone one with bad intentions to reverse engineer a mobile app, like:

For MitM atttacks - mitmproxy

An interactive TLS-capable intercepting HTTP proxy for penetration testers and software developers.

For static analysis - MobSF - Mobile Security Framework

Mobile Security Framework is an automated, all-in-one mobile application (Android/iOS/Windows) pen-testing framework capable of performing static analysis, dynamic analysis, malware analysis and web API testing.

For runtime code instrumentation - Frida

Inject your own scripts into black box processes. Hook any function, spy on crypto APIs or trace private application code, no source code needed. Edit, hit save, and instantly see the results. All without compilation steps or program restarts.

Despite this tools exist I still encourage you to employ as many defense techniques as you can afford into your mobile app, because not every attacker as the knowledge or is willing to spent too much time in your mobile app, when they have easier targets to attack.

POSSIBLE SOLUTION

Whats a true way to deal with this??

No true way exists, it's all about your special use case and how much resources you have and can afford to employ and are required by law to do so.

For APIs serving mobile apps you can employ the Mobile App Attestation concept that will allow your API server to have an high degree of confidence about what is doing the request to the API server, is it your genuine and untampered mobile app or is an attacker.

I recommend you to read this answer I gave to the question How to secure an API REST for mobile app?, specially the sections Securing the API Server and A Possible Better Solution.

DO YOU WANT TO GO THE EXTRA MILE?

In any response to a security question I always like to reference the excellent work from the OWASP foundation.

For Mobile Apps

OWASP Mobile Security Project - Top 10 risks

The OWASP Mobile Security Project is a centralized resource intended to give developers and security teams the resources they need to build and maintain secure mobile applications. Through the project, our goal is to classify mobile security risks and provide developmental controls to reduce their impact or likelihood of exploitation.

OWASP - Mobile Security Testing Guide:

The Mobile Security Testing Guide (MSTG) is a comprehensive manual for mobile app security development, testing and reverse engineering.

For APIS

OWASP API Security Top 10

The OWASP API Security Project seeks to provide value to software developers and security assessors by underscoring the potential risks in insecure APIs, and illustrating how these risks may be mitigated. In order to facilitate this goal, the OWASP API Security Project will create and maintain a Top 10 API Security Risks document, as well as a documentation portal for best practices when creating or assessing APIs.

How do I call REST API with bearer token from an Android app?

You can use retrofit

Retrofit is a REST Client for Java and Android. It makes it relatively
easy to retrieve and upload JSON (or other structured data) via a REST
based webservice. source

also check this answer

How send http request in android app to access REST API

http://breaking-catch22.com/?p=12

public class AndroidApp extends Activity {  

String URL = "http://the/url/here";
String result = "";
String deviceId = "xxxxx" ;
final String tag = "Your Logcat tag: ";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

final EditText txtSearch = (EditText)findViewById(R.id.txtSearch);
txtSearch.setOnClickListener(new EditText.OnClickListener(){
public void onClick(View v){txtSearch.setText("");}
});

final Button btnSearch = (Button)findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
String query = txtSearch.getText().toString();
callWebService(query);

}
});

} // end onCreate()

public void callWebService(String q){
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(URL + q);
request.addHeader("deviceId", deviceId);
ResponseHandler<string> handler = new BasicResponseHandler();
try {
result = httpclient.execute(request, handler);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
httpclient.getConnectionManager().shutdown();
Log.i(tag, result);
} // end callWebService()
}

Better approach to call rest api from android

Use Retrofit

public interface GitHubService {
@GET("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);

@GET("users/repos/{id}")
Call<Repo> getRepo(@Path("id") String id);

}

Any kind of url changes can be done in this interface

Initialization of retrofit with base url

Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.build();

GitHubService service = retrofit.create(GitHubService.class);

Consuming Api

Call<List<Repo>> repos = service.listRepos("octocat");
repos.enqueue(new Callback<List<Repo>>() {
@Override
public void onResponse(Call<List<Repo>> call, Response<List<Repo>> response) {
//Do something with response
}

@Override
public void onFailure(Call<List<String>> call, Throwable t) {
//handle failure
}
});

For more Retrofit



Related Topics



Leave a reply



Submit