How to call a RESTful web service with Android?

I wrote a REST web service in the NetSE IDE using the Jersey and Java framework.

For each request, the user must specify a username and password, I know that this authentication is not the best practice (using the curl command, for example: curl -u username:password -X PUT http://localhsot:8080/user ).

Now I want to call the REST web service from an Android class.

How should I do it?

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

+46
java android rest authorization web-services
May 18 '11 at 15:09
source share
10 answers

This is an example of the 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(); } } 
+18
Aug 08 '11 at 4:01
source share

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




Defining a REST Endpoint

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



Getting a specific service

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



REST Endpoint Call

 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 json serialization and deserailization for you. You can also customize serialization and deserialization.

 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(); 
+13
May 09 '14 at 7:49
source share

I am using this REST Client for my Android. It looks great. Good job Luke.

http://lukencode.com/2010/04/27/calling-web-services-in-android-using-httpclient/

+6
May 18 '11 at 17:46
source share

Stop everything you do! :)

Deploy the RESTful client as SERVICE and delegate the intensive network material to an activity-independent component: SERVICE.

Watch this insightful video http://www.youtube.com/watch?v=xHXn3Kg2IQE , where Virgil Dobzhansky explains his approach to this problem ...

+6
May 31 '13 at 8:01
source share

I used OkHttpClient to call a calm web service. It is 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() 
+1
Jun 10 '16 at 3:12
source share

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"); 
+1
Aug 22 '16 at
source share

What is the source code? 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 this REST service.

For JSON ↔ Matching objects on both sides (Android, Java back-end) you can use GSON.

0
Jun 21 '14 at 4:57
source share

Maybe it's late or maybe you already used it before, but there is another one called ksoap , and this is pretty surprising .. It also includes timeouts and can effectively analyze any SOAP-based web service. I also made a few changes according to my analysis. Look it up

0
Jun 25 '15 at 5:07
source share

Follow the steps below to use Restful in android.

Step1

Create an empty android project.

Step2

Internet permission required. write the code below in the AndroidManifest.xml file.

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

Step3

Requires RestFul URL that is running on another server or on the same machine.

Step4

Make a RestFul client that extends AsyncTask. See RestFulPost.java.

Step5

Create a DTO class for the 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 information and full code, visit http://javaant.com/consume-a-restful-webservice-in-android/#.VwzbipN96Hs

0
Apr 12 '16 at 11:37
source share

Here is my library that I created for a simple call to Webservice,

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

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

Here is a demonstration of use.

https://github.com/vishalchhodwani1992/httpLibrary

0
Feb 22 '17 at 9:53 on
source share



All Articles