Home » Android » java – Http Ok3 Returns two responses-Exceptionshub

java – Http Ok3 Returns two responses-Exceptionshub

Posted by: admin February 26, 2020 Leave a comment

Questions:

I am connecting black box backend, I have no control over the source and cannot modify the backend, using Ok Http 3. But for some reason, I am getting two results and I don’t know what’s going on. I suspect two threads are becoming active. But I don’t know how to stop it. I tried both Synchronous and Asynchronous connection to no effect. I am new to Ok Http 3, so I am not sure what I am doing wrong.

I/Results: {"TotalResultsCount":3,"Results":[{

I/Results: {"TotalResultsCount":24,"Results":[

Here’s is my synchronous code

class CallBackendSync extends AsyncTask {

        OkHttpClient client = new OkHttpClient();
        JSONObject resultsObject = null;

        @Override
        protected Object doInBackground(Object [] objects) {
            String searchTerm = (String) objects[0];
            String url = (String) objects[1];
            String token = (String) objects[2];
            String results = "";

            //Search Body
            RequestBody searchBody = new FormBody.Builder()
                    .add("QueryText", searchTerm)
                    .add("Categories", "")
                    .add("ChargeOutPerMinuteFrom", "0")
                    .add("ChargeOutPerMinuteTo", "0")
                    .add("maxDistance", "0")
                    .add("longitude", "0")
                    .add("latitude", "0")
                    .add("page", "0")
                    .build();
            //Create request
            Request.Builder builder = new Request.Builder();
            builder.url(url);
            builder.addHeader("Accept", "application/json");
            if (token != null) {
                builder.addHeader("Authorization", token);
            }
            builder.post(searchBody);
            Request request = builder.build();
            try {
                Response response = client.newCall(request).execute();
                results = results + response.body().string();
                resultsObject = new JSONObject(results);
                Log.i("Results", results);
                return resultsObject;
            }catch (Exception e){
                e.printStackTrace();
            }
            return null;
        }

        protected void onPostExecute(String s){
            super.onPostExecute(s);
            displayResults(resultsObject);
        }
    }

I am calling the backend from MainActivity using the code fragment below

CallBackendSync sync = new CallBackendSync();
        String [] params = {searchTerm, serverBaseUrl + url, accessToken};
        sync.execute(params);

Any ideas about what’s going wrong will be much appreciated.

How to&Answers: