Anand
Anand

Reputation: 1959

How to perform API call in the background?

I want to create a simple app which is intend to call a API in POST method when a button clicks.The app workflow will be like this; user enter the url and a timeout value, and press start button. The API will called in the provided url and it will again and again call according to the timeout value provided. When user press the stop button,all activity should stop.The API call will not provide any data in response. I simply want to call that API in POST method.In order to achieve this I written the API call in a service.

The problem Iam facing is

  1. The POST method doesn't working.

2.How can I call this api in background according to the timeout value provided.?

What I have Done

My MainActivity

  url   = (EditText)findViewById(R.id.editText3);
        timeOut   = (EditText)findViewById(R.id.editText5);
        Button clickButton = (Button) findViewById(R.id.start);
        clickButton.setOnClickListener( new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                Intent intent = new Intent(MainActivity.this, APIService.class);
                Bundle bund = new Bundle();

                bund.putString("url",url.getText().toString());
                bund.putString("timeout",timeOut.getText().toString());
                intent.putExtras(bund);
                startService(intent);


            }
        });

        Button stopbutton = (Button) findViewById(R.id.stop);
        stopbutton.setOnClickListener( new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub


                Intent intent = new Intent(MainActivity.this, APIService.class);
                stopService(intent);

            }
        });

My API Service class

public APIService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        Toast.makeText(this, " Client API Service Started", Toast.LENGTH_LONG).show();
        super.onCreate();
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "Client API Service Started", Toast.LENGTH_LONG).show();
        String WEBURL;
        String TimeOut;
        Bundle bund = intent.getExtras();
        WEBURL=bund.getString("url");
        TimeOut=bund.getString("timeout");
        String URL= "http://"+WEBURL+"/API/ReportSubscription/GetAllReportSubscription?subscriptionUR="+WEBURL;
        new HttpRequestTask(
                new HttpRequest(URL, HttpRequest.POST),
                new HttpRequest.Handler() {
                    @Override
                    public void response(HttpResponse response) {
                        if (response.code == 200) {
                            Log.d(this.getClass().toString(), "Request successful!");
                        } else {
                            Log.e(this.getClass().toString(), "Request unsuccessful: " + response);
                        }
                    }
                }).execute();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Client API Service Stopped", Toast.LENGTH_LONG).show();
    }
}

I Used compile 'com.apptakk.http_request:http-request:0.1.2' for Web API call.Any help is appriciated

Upvotes: 1

Views: 13338

Answers (2)

bvk256
bvk256

Reputation: 1903

You can use OkHttp for this. See this tutorial for more: https://www.vogella.com/tutorials/JavaLibrary-OkHttp/article.html

// avoid creating several instances, should be singleon
OkHttpClient client = new OkHttpClient();

String weburl = bund.getString("url");

RequestBody requestBody = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("subscriptionUR", weburl)
        .build();

Request request = new Request.Builder()
                     .url("http://"+weburl+"/API/ReportSubscription/GetAllReportSubscription")
.post(requestBody)
                     .build();

 client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        // Do something when request failed
                        e.printStackTrace();
                        Log.d(TAG, "Request Failed.");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if(!response.isSuccessful()){
                            throw new IOException("Error : " + response);
                        }else {
                            Log.d(TAG,"Request Successful.");
                        }

                        // Read data in the worker thread
                        final String data = response.body().string();
                    }
                });

Upvotes: 1

manishm
manishm

Reputation: 81

  1. First make sure your API is working by testing through Postman. After you have make sure that API is working fine from the backend itself then the problem is from your mobile side calling that API. I would really recommend retrofit (https://square.github.io/retrofit/) to try out API calling task asynchronously because its really easy and standard way .You simply using POST method in api by passing your time out value as a parameter and your api url as base url.

  2. You can use service in android to execute in the background i.e your API calling

Upvotes: 2

Related Questions