[java] How to call a RESTful web service from Android?

I have written a REST web service in Netbean IDE using Jersey Framework and Java.

For every request the user needs to provide a username and a password, I know that this authentication is not a best practice (using a curl command like: curl -u username:password -X PUT http://localhsot:8080/user).

Now I want to call a REST web service from an Android Class.

How should I do it?

I have an Android Class which uses DefaultHttpClient and CredentialUsernameAndPassword, but when I run it in Eclipse, sometimes I get a runtime exception or SDK exception.

This question is related to java android web-services rest authorization

The answer is


What back-end? If JAVA then you can use REST with Java (JAX-RS) using Jersey.

On the Android side you can use this simple RestClient to work with that REST service.

For JSON <--> Object mapping on both sides (Android, Java back-end) you can use GSON.


This is an sample restclient class

public class RestClient
{
    public enum RequestMethod
    {
        GET,
        POST
    }
    public int responseCode=0;
    public String message;
    public String response;
    public void Execute(RequestMethod method,String url,ArrayList<NameValuePair> headers,ArrayList<NameValuePair> params) throws Exception
    {
        switch (method)
        {
            case GET:
            {
                // add parameters
                String combinedParams = "";
                if (params!=null)
                {
                    combinedParams += "?";
                    for (NameValuePair p : params)
                    {
                        String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8");
                        if (combinedParams.length() > 1)
                            combinedParams += "&" + paramString;
                        else
                            combinedParams += paramString;
                    }
                }
                HttpGet request = new HttpGet(url + combinedParams);
                // add headers
                if (headers!=null)
                {
                    headers=addCommonHeaderField(headers);
                    for (NameValuePair h : headers)
                        request.addHeader(h.getName(), h.getValue());
                }
                executeRequest(request, url);
                break;
            }
            case POST:
            {
                HttpPost request = new HttpPost(url);
                // add headers
                if (headers!=null)
                {
                    headers=addCommonHeaderField(headers);
                    for (NameValuePair h : headers)
                        request.addHeader(h.getName(), h.getValue());
                }
                if (params!=null)
                    request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
                executeRequest(request, url);
                break;
            }
        }
    }
    private ArrayList<NameValuePair> addCommonHeaderField(ArrayList<NameValuePair> _header)
    {
        _header.add(new BasicNameValuePair("Content-Type","application/x-www-form-urlencoded"));
        return _header;
    }
    private void executeRequest(HttpUriRequest request, String url)
    {
        HttpClient client = new DefaultHttpClient();
        HttpResponse httpResponse;
        try
        {
            httpResponse = client.execute(request);
            responseCode = httpResponse.getStatusLine().getStatusCode();
            message = httpResponse.getStatusLine().getReasonPhrase();
            HttpEntity entity = httpResponse.getEntity();

            if (entity != null)
            {
                InputStream instream = entity.getContent();
                response = convertStreamToString(instream);
                instream.close();
            }
        }
        catch (Exception e)
        { }
    }

    private static String convertStreamToString(InputStream is)
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try
        {
            while ((line = reader.readLine()) != null)
            {
                sb.append(line + "\n");
            }
            is.close();
        }
        catch (IOException e)
        { }
        return sb.toString();
    }
}

I used OkHttpClient to call restful web service. It's very simple.

OkHttpClient httpClient = new OkHttpClient();
Request request = new Request.Builder()
                .url(url)
                .build();

Response response = httpClient.newCall(request).execute();
String body = response.body().string()

Using Spring for Android with RestTemplate https://spring.io/guides/gs/consuming-rest-android/

// The connection URL 
String url = "https://ajax.googleapis.com/ajax/" + 
    "services/search/web?v=1.0&q={query}";

// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate();

// Add the String message converter
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());

// Make the HTTP GET request, marshaling the response to a String
String result = restTemplate.getForObject(url, String.class, "Android");

Stop with whatever you were doing ! :)

Implement the RESTful client as a SERVICE and delegate the intensive network stuff to activity independent component: a SERVICE.

Watch this insightful video http://www.youtube.com/watch?v=xHXn3Kg2IQE where Virgil Dobjanschi is explaining his approach(es) to this challenge...


Recently discovered that a third party library - Square Retrofit can do the job very well.


Defining REST endpoint

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

Getting the concrete service

RestAdapter restAdapter = new RestAdapter.Builder()
    .setEndpoint("https://api.github.com")
    .build();
GitHubService service = restAdapter.create(GitHubService.class);

Calling the REST endpoint

List<Repo> repos = service.listRepos("octocat",new Callback<List<User>>() { 
    @Override
    public void failure(final RetrofitError error) {
        android.util.Log.i("example", "Error, body: " + error.getBody().toString());
    }
    @Override
    public void success(List<User> users, Response response) {
        // Do something with the List of Users object returned
        // you may populate your adapter here
    }
});

The library handles the json serialization and deserailization for you. You may customize the serialization and deserialization too.

Gson gson = new GsonBuilder()
    .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
    .registerTypeAdapter(Date.class, new DateTypeAdapter())
    .create();

RestAdapter restAdapter = new RestAdapter.Builder()
    .setEndpoint("https://api.github.com")
    .setConverter(new GsonConverter(gson))
    .build();

Follow the below steps to consume RestFul in android.

Step1

Create a android blank project.

Step2

Need internet access permission. write the below code in AndroidManifest.xml file.

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

Step3

Need RestFul url which is running in another server or same machine.

Step4

Make a RestFul Client which will extends AsyncTask. See RestFulPost.java.

Step5

Make DTO class for RestFull Request and Response.

RestFulPost.java

package javaant.com.consuming_restful.restclient;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import com.google.gson.Gson;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import java.util.Map;
import javaant.com.consuming_restful.util.Util;
/**
 * Created by Nirmal Dhara on 29-10-2015.
 */
public class RestFulPost extends AsyncTask<map, void,="" string=""> {
    RestFulResult restFulResult = null;
    ProgressDialog Asycdialog;
    String msg;
    String task;
    public RestFulPost(RestFulResult restFulResult, Context context, String msg,String task) {
        this.restFulResult = restFulResult;
        this.task=task;
        this.msg = msg;
        Asycdialog = new ProgressDialog(context);
    }
    @Override
    protected String doInBackground(Map... params) {
        String responseStr = null;
        Object dataMap = null;
        HttpPost httpost = new HttpPost(params[0].get("url").toString());

        try {
            dataMap = (Object) params[0].get("data");
            Gson gson = new Gson();
            Log.d("data  map", "data map------" + gson.toJson(dataMap));
            httpost.setEntity(new StringEntity(gson.toJson(dataMap)));
            httpost.setHeader("Accept", "application/json");
            httpost.setHeader("Content-type", "application/json");
            DefaultHttpClient httpclient= Util.getClient();
            HttpResponse response = httpclient.execute(httpost);
            int statusCode = response.getStatusLine().getStatusCode();
            Log.d("resonse code", "----------------" + statusCode);

            if (statusCode == 200)
                responseStr = EntityUtils.toString(response.getEntity());
            if (statusCode == 404) {
                responseStr = "{\n" +
                        "\"status\":\"fail\",\n" +
                        " \"data\":{\n" +
                        "\"ValidUser\":\"Service not available\",\n" +
                        "\"code\":\"404\"\n" +
                        "}\n" +
                        "}";
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return responseStr;
    }
    @Override
    protected void onPreExecute() {
        Asycdialog.setMessage(msg);
        //show dialog
        Asycdialog.show();
        super.onPreExecute();
    }
    @Override
    protected void onPostExecute(String s) {
        Asycdialog.dismiss();
        restFulResult.onResfulResponse(s,task);
    }
}

For more details and complete code please visit http://javaant.com/consume-a-restful-webservice-in-android/#.VwzbipN96Hs


Perhaps am late or maybe you've already used it before but there is another one called ksoap and its pretty amazing.. It also includes timeouts and can parse any SOAP based webservice efficiently. I also made a few changes to suit my parsing.. Look it up


Here is my Library That I have created for simple Webservice Calling,

You can use this by adding a one line gradle dependency -

compile 'com.scantity.ScHttpLibrary:ScHttpLibrary:1.0.0'

Here is the demonstration of using.

https://github.com/vishalchhodwani1992/httpLibrary


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to web-services

How do I POST XML data to a webservice with Postman? How to send json data in POST request using C# org.springframework.web.client.HttpClientErrorException: 400 Bad Request How to call a REST web service API from JavaScript? The request was rejected because no multipart boundary was found in springboot Generating Request/Response XML from a WSDL How to send a POST request using volley with string body? How to send post request to the below post method using postman rest client How to pass a JSON array as a parameter in URL Postman Chrome: What is the difference between form-data, x-www-form-urlencoded and raw

Examples related to rest

Access blocked by CORS policy: Response to preflight request doesn't pass access control check Returning data from Axios API Access Control Origin Header error using Axios in React Web throwing error in Chrome JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value How to send json data in POST request using C# How to enable CORS in ASP.net Core WebAPI RestClientException: Could not extract response. no suitable HttpMessageConverter found REST API - Use the "Accept: application/json" HTTP Header 'Field required a bean of type that could not be found.' error spring restful API using mongodb MultipartException: Current request is not a multipart request

Examples related to authorization

How to send custom headers with requests in Swagger UI? How do you create a custom AuthorizeAttribute in ASP.NET Core? ASP.NET Web API : Correct way to return a 401/unauthorised response How to get http headers in flask? How to define the basic HTTP authentication using cURL correctly? basic authorization command for curl MongoDB "root" user How to use basic authorization in PHP curl How to get user name using Windows authentication in asp.net? Python requests library how to pass Authorization header with single token