Тайм-аут запроса залпа с использованием фьючерсов - PullRequest
0 голосов
/ 08 ноября 2019

Я хочу создать синхронный запрос к службе REST, используя библиотеку Volley. Я попытался настроить «Помощник» для управления запросом с использованием объекта Future и тайм-аута 15 с, это мой код:

import android.app.Application;
import android.content.Context;
import android.content.OperationApplicationException;
import android.util.Log;

import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.RequestFuture;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class RestHelper {

    private static RestHelper instance = null;
    private static String L="LOG";

    public static synchronized RestHelper getInstance(Context context)
    {
        if (null == instance)
            instance = new RestHelper(context);
        return instance;
    }

    private RequestQueue requestQueue;
    private RestHelper(Context context)
    {
        requestQueue = Volley.newRequestQueue(context.getApplicationContext());
    }


    private JsonElement get(String url) throws InterruptedException, ExecutionException, TimeoutException {
        RequestFuture<JSONObject> future = RequestFuture.newFuture();
        JsonObjectRequest request = new JsonObjectRequest(url, null, future, future);
        requestQueue.add(request);
        JSONObject obj;
        try{
            obj=future.get(15, TimeUnit.SECONDS);
        }catch (InterruptedException | ExecutionException e){
            if(e.getCause() instanceof VolleyError) {
                NetworkResponse networkResponse = ((VolleyError) e.getCause()).networkResponse;
                Log.e(L,"Network error, HTTP status: "+networkResponse.statusCode);
                Log.e(L,"Network error, HTTP content: "+new String(networkResponse.data));
            }else
                Log.e(L,"Network error: "+e.getMessage());
            throw e;
        }catch (TimeoutException e){
            Log.e(L,"Network timeout");
            throw e;
        }
        return parseResponse(obj);
    }

    private JsonElement parseResponse(JSONObject obj){
        JsonParser parser = new JsonParser();
        JsonElement mJson =  parser.parse(obj.toString());
        Gson gson = new Gson();
        Return ret = gson.fromJson(mJson, Return.class);
        if(!ret.isSuccess())
            throw new RuntimeException(ret.getError());
        return mJson;
    }
}

Удаленная конечная точка называется (я нашел журнал подключений на удаленном сервере), но будущий объект всегда отбрасывается для тайм-аута.

Я прочитал кое-что о проблеме с потоком, но, насколько я знаю, RequestQueue сделан с использованием основного контекста приложения. Это достаточно? Что еще мне не хватает?

1 Ответ

0 голосов
/ 08 ноября 2019

Вы звонили startQueue? Из вашего кода у вас его нет.

На основании официальной документации .

// Set up the network to use HttpURLConnection as the HTTP client.
Network network = new BasicNetwork(new HurlStack());

// Instantiate the RequestQueue with the cache and network.
requestQueue = new RequestQueue(cache, network);

// Start the queue
requestQueue.start();
...