1

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.

rahmatNazali
  • 35
  • 1
  • 9

6 Answers6

2

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

Pratik Vyas
  • 644
  • 7
  • 20
2

AsyncTask Example

Personally I also prefer Retrofit/Volley depending on the project need.

If you want to set the header to you (testApi) Rest API.(Basic Authorization)

String credentials = email + ":" + password;
String basicAuth = "Basic " + new String(new Base64().encode(credentials.getBytes()));
connection.setRequestProperty ("Authorization", basicAuth); 
connection..setRequestProperty("Content-Language", "en-US");

Note:

  1. Network operations/call cannot be done in the main thread. You need to run it from another thread, asynchronous task or an intent service

  2. All UI operation should be done onPostExecute,onPreExecute

Call AsyncTask where you want

The below code may help you.

    import android.app.Activity;
    import android.os.AsyncTask;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.widget.Toast;
    import org.json.JSONObject;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLEncoder;
    import java.util.HashMap;
    import java.util.Map;

    public class MainActivity extends AppCompatActivity {
        String TEST_URL="http://172.16.68.4:8080/testApi";
        Activity activity;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            activity=MainActivity.this;

            new PostAsyncTask().execute();

        }

        private class PostAsyncTask extends AsyncTask<String,Void,JSONObject> {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected JSONObject doInBackground(String... params) {
                String value="test";
                Map postData = new HashMap<>();
                postData.put("key",value);
                return post(TEST_URL,postData);
            }

            @Override
            protected void onPostExecute(JSONObject response) {
                super.onPostExecute(response);
                //All your UI operation can be performed here
                //Response string can be converted to JSONObject/JSONArray like
                try {
                    Toast.makeText(activity, String.format("%s : %s",response.getString("status"),response.getString("name")), Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(activity, String.format("%s","Something went wrong!!!!!!"), Toast.LENGTH_LONG).show();

                }
                System.out.println(response);
            }
        }
         /**
         * Method allows to HTTP POST request to the server to send data to a specified resource
         * @param REQUEST_URL URL of the API to be requested
         * @param params parameter that are to be send in the "body" of the request Ex: parameter=value&amp;also=another
         * returns response as a JSON object
         */
        public JSONObject post(String REQUEST_URL,Map<String, Object> params) {
            JSONObject jsonObject = null;
            BufferedReader reader = null;
            try { URL url = new URL(REQUEST_URL);
                StringBuilder postData = new StringBuilder();
                for (Map.Entry<String, Object> param : params.entrySet()) {
                    if (postData.length() != 0) postData.append('&');
                    postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                    postData.append('=');
                    postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
                }
                byte[] postDataBytes = postData.toString().getBytes("UTF-8");

                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                connection.setConnectTimeout(8000);
                connection.setRequestMethod("POST");
                connection.setUseCaches(false);
                connection.setDoOutput(true);
                connection.getOutputStream().write(postDataBytes);
                connection.connect();
                StringBuilder sb;
                int statusCode = connection.getResponseCode();
                if (statusCode == 200) {
                    sb = new StringBuilder();
                    reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line);
                    }
                    jsonObject = new JSONObject(sb.toString());
                }
                connection.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            return jsonObject;
        }
    }
Andan H M
  • 793
  • 12
  • 18
1

Rahmat. You can try on Android Volley Library if you wish to send POST request to your Web API. You can refer the links below.

Android Volley Library

Android Volley Link Here

Tutorial

Android Hive Volley Tutorial

Dzone Volley Tutorial

Yih Wei
  • 537
  • 3
  • 21
  • Hi Tan Yih Wei! Thankyou for your kind answer and suggestion regarding Volley library, it's been very informing :)) – rahmatNazali Jun 08 '17 at 02:35
1

You can use RestTemplate using Restful service, it's pretty easy. Below is a sample code, in which I post an Object.

public MasterObject setMasterByBatch(MasterObject masterObject) {
    try {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        masterObject = restTemplate.postForObject(yourUrl, masterObject, MasterObject.class);          

    } catch (Exception e) {
        e.printStackTrace();
        Log.e("masterObjPost_WsCli_EX", e.toString());
    }
    return masterObject;
}

This needs few dependencies in your build.gradle(Module: app):

dependencies {
compile 'org.springframework.android:spring-android-rest-template:1.0.1.RELEASE'
compile 'com.fasterxml.jackson.core:jackson-core:2.6.0'
compile 'com.fasterxml.jackson.core:jackson-databind:2.6.0'
}

If shows any error regarding org.springframework you might need to download and insert spring library

vss
  • 1,093
  • 1
  • 20
  • 33
1

Personally I prefer Retrofit, it's really easy and really nice to use

http://square.github.io/retrofit/

Saik Caskey
  • 500
  • 4
  • 18
0

AndroidManifest

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

MainActivity

        API apiInterface = RestClient.getRetrofit().create(API.class);
        //JsonObject objFilterData = new JsonObject();
        //objFilterData.addProperty("params", "0");
        Call<JsonObject> call = apiInterface.apiname("0");
        call.enqueue(new Callback<JsonObject>() {
            @Override
            public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                // check your full URL
                String url = response.raw().request().url().toString();

                JsonObject jsonObject = new Gson().fromJson(response.body(), JsonObject.class);
                //your response in json Object
            }

            @Override
            public void onFailure(Call<JsonObject> call, Throwable t) {
                Toast.makeText(MainActivity.this, "" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

RestClient

public class RestClient {

    public static String base_url = "your base url";
    public static Retrofit retrofit;

    public static Retrofit getRetrofit() {
        if (retrofit == null) {

            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(100, TimeUnit.SECONDS)
                    .writeTimeout(100, TimeUnit.SECONDS)
                    .readTimeout(100, TimeUnit.SECONDS).build();

            retrofit = new Retrofit.Builder()
                    .baseUrl(base_url)
                    .client(client)
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }

        return retrofit;
    }
}

interface API Class

public interface API {



    @FormUrlEncoded
    @POST("apiname")
    Call<JsonObject> apiname(@Field("params") String customer_id);
    
     //@Headers("Content-Type:application/json")
     //@POST("updateselleraddress")
     //Call<JsonObject> updateselleraddress(@Body String body);

}

values/xml/network_security_config.xml

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true" />
</network-security-config>

Retrofit Dependencies

 implementation 'com.squareup.okhttp3:okhttp:5.0.0-alpha.7'
 implementation 'com.squareup.okhttp3:logging-interceptor:5.0.0-alpha.7'
 implementation 'com.squareup.retrofit2:retrofit:2.9.0'
 implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
 implementation 'com.squareup.retrofit2:converter-scalars:2.9.0'

if you need Response class

    @SerializedName("data")
    @Expose
    private ArrayList<Data> data;

    public ArrayList<Data> getData() {
        return data;
    }

    public void setData(ArrayList<Data> data) {
        this.data = data;
    }
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – lemon May 23 '22 at 11:26