Search code examples
androidapiandroid-studio

Calling a POST API on android


From Android, I'm trying to request a simple POST-API that responses with a simple JSON object.

Say, I have a simple API (1.1.1.1/testApi) that respons with a JSON object that contains:

  • status: status value
  • name: name value

Calling the API using Postman works like a charm, so I assume that my API was fine.

I already tried some of the links below:

  1. AsyncTask: there is no example on how to call the CallApi object and parse the API address (e.g. URL), so there is always an error when I try to invoke the object.
  2. Apache HTTP Client: as the link said, nearly all of the answer are deprecated for Android 6.0
  3. Retrofit: seems usable, but I can't find a proper example to use this in my case

I did take my time to search solutions regarding this, but afaik there is no "easy" way to call a POST-API.

Is there any simple method that takes an URL input, then returns a JSON object?

Let me know if this was a duplicated question.

Thanks in advance.


Solution

  • Hello I Have working Retrofit Example try it on your manner

    Let's start

    1) Gradle

        compile 'com.google.code.gson:gson:2.2.4'
        compile 'com.squareup.okhttp:okhttp:2.4.0'
        compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
        compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
        compile 'com.squareup.okhttp3:logging-interceptor:3.0.1' 
    

    2) Interface

    public interface ServiceInterface {
    @GET(HttpConstants.USERDATAJSON)
        Call<ListData>taskData(@Query("method")String method,@Query("stdID")int stdID);
    }
    

    3) Service Class

    public class ServiceClass {
        static ServiceInterface serviceInterface;
    //    public static final String baseUrl= HttpConstants.BASE_URL_GEONAME;
        public static final String baseUrl= HttpConstants.baseUrl;
    
        public static ServiceInterface connection(){
            if(serviceInterface==null){
                HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
                interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                OkHttpClient client = new OkHttpClient();
                client.interceptors().add(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Response response=chain.proceed(chain.request());
                        return response;
                    }
                });
                Retrofit retrofit = new Retrofit.Builder()
                        .client(client)
                        .addConverterFactory(GsonConverterFactory.create())
                        .baseUrl(baseUrl)
                        .build();
                serviceInterface=retrofit.create(ServiceInterface.class);
            }
            return serviceInterface;
        }
    }
    

    4) Calling the method from activity

    public void getTaskData(){
            ServiceInterface serviceInterface=ServiceClass.connection();
            Call<ListData> call=serviceInterface.taskData("getAllUsersSimple",0);
            call.enqueue(new Callback<ListData>() {
                @Override
                public void onResponse(Response<ListData> response, Retrofit retrofit) {
                    Log.v("@@@Response",""+response.toString());
                    if(response.isSuccess()){
                        listData=response.body();
                        dataList=listData.getData();
                        printStudentDetails(dataList);
    
                    }
                }
    
                @Override
                public void onFailure(Throwable t) {
                    Log.v("@@@Failure"," Message"+t.getMessage());
                }
            });
        }
    

    5) The Pojo

    public class ListData {
    
        @SerializedName("data")
        @Expose
        private List<DataPojo> data = null;
        @SerializedName("code")
        @Expose
        private Integer code;
        @SerializedName("message")
        @Expose
        private String message;
    
        public List<DataPojo> getData() {
            return data;
        }
    
        public void setData(List<DataPojo> data) {
            this.data = data;
        }
    
        public Integer getCode() {
            return code;
        }
    
        public void setCode(Integer code) {
            this.code = code;
        }
    
        public String getMessage() {
            return message;
        }
    
        public void setMessage(String message) {
            this.message = message;
        }
    
    }
    public class DataPojo {
    
        @SerializedName("user_id")
        @Expose
        private String userId;
        @SerializedName("user_name")
        @Expose
        private String userName;
        @SerializedName("user_age")
        @Expose
        private String userAge;
    
        public String getUserId() {
            return userId;
        }
    
        public void setUserId(String userId) {
            this.userId = userId;
        }
    
        public String getUserName() {
            return userName;
        }
    
        public void setUserName(String userName) {
            this.userName = userName;
        }
    
        public String getUserAge() {
            return userAge;
        }
    
        public void setUserAge(String userAge) {
            this.userAge = userAge;
        }
    
    }
    

    You can create your pojo using this link http://www.jsonschema2pojo.org/

    For more reference visit the link https://github.com/pratikvyas1991/NetworkingExample/tree/master/app