How to call a RESTful web service from Android?

后端 未结 9 1748
生来不讨喜
生来不讨喜 2020-11-27 10:58

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

相关标签:
9条回答
  • 2020-11-27 11:22

    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();
    
    0 讨论(0)
  • 2020-11-27 11:24

    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

    0 讨论(0)
  • 2020-11-27 11:26

    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...

    0 讨论(0)
  • 2020-11-27 11:26

    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.

    0 讨论(0)
  • 2020-11-27 11:26

    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

    0 讨论(0)
  • 2020-11-27 11:30

    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();
        }
    }
    
    0 讨论(0)
提交回复
热议问题