Как отправить только один запрос с HttpURLConnection - PullRequest
0 голосов
/ 27 марта 2019

Я новичок в коде, и я впервые задаю вопрос.

  1. Я использую следующий код для отправки запроса на сервер.
  2. Я вызвал функцию один раз, но запрос отправляется дважды.
  3. Результат, полученный с сервера, получен из результата второго запроса.

Как отправить только одинзапрос к серверу

Класс, в котором хранятся все мои исполняемые файлы

public class ServerRunnables implements Runnable {
    Account currentAccount = Account.getInstance();

    private String result = "";
    private Context context;
    private Boolean callSuccess = true;

    int serviceCalled;
    String email;
    String password;
    String username;
    int coinChanges;

    String urlString = "http://10.0.2.2/MobileCoin/" + services[serviceCalled];
    String requiredParams;

    public ServerRunnables(Context context,
                           int serviceCalled,
                           String email,
                           String password,
                           String username,
                           int coinChanges) {

        this.context = context;
        this.serviceCalled = serviceCalled;
        this.email = email;
        this.password = password;
        this.username = username;
        this.coinChanges = coinChanges;
    }

    public void run() {
        urlString = "http://10.0.2.2/MobileCoin/" + services[serviceCalled];
        switch (serviceCalled) {
            case SERVICE_RANDOM_COIN:
                generateCoinServiceCalled();
                break;
            default:
                break;
        }
    }



    private void generateCoinServiceCalled() {

        requiredParams = "email=" + email;
        urlString = urlString + "?" + requiredParams;

        getMethodCalled(urlString);

        callSuccess = true;
        String message1 = "";

        if (result.equals(ServerConstants.RANDOM_COIN_EMPTY)) {
            callSuccess = false;
            message1 = "No Data Received";
        } else if (result.equals(ServerConstants.RANDOM_COIN_FAIL)) {
            callSuccess = false;
            message1 = "Data Does not Exist.";
        } else if (result.equals(ServerConstants.CONNECTION_ERROR)) {
            callSuccess = false;
            message1 = "Connection Error, Check Server";
        } else {
            message1 = "Coin Generated : " + Integer.parseInt(result);
        }

        coinChanges(currentAccount.getCoin() + Integer.parseInt(result));
    }

    private void getMethodCalled(String urlString) {
        result = "";

        try {
            URL url = new URL(urlString);

            HttpURLConnection hc = (HttpURLConnection) url.openConnection();
            int length = hc.getContentLength();

            InputStream input = url.openStream();
            byte[] binput = new byte[length];
            int readSize = input.read(binput);

            result = new String(binput).trim();
            input.close();
        } catch (Exception e) {
            Log.e("Net", "Error", e);
            result = ServerConstants.CONNECTION_ERROR;
        }

        Log.i(TAG, result);
    }
}

Начните отправку запроса отсюда

public class ServletsAPI {
    public static Context context;

    public static void randomCoinAPI(String email){
        ServerRunnables newRunnable =
                new ServerRunnables(context, ServerRunnables.SERVICE_RANDOM_COIN, email, null, null, 0);
        new Thread(newRunnable).start();
    }
}

Ответы [ 2 ]

0 голосов
/ 27 марта 2019

Я нашел ошибку:

InputStream input = url.openStream();

изменено на

InputStream input = hc.getInputStream();
0 голосов
/ 27 марта 2019

Почему бы вам не использовать Retrofit для простой обработки http-запроса? Если вы интегрируетесь с RxJava , вы можете управлять своим запросом асинхронно.

...