Как получить доступ к ответу сервера в Android? - PullRequest
0 голосов
/ 05 декабря 2018

Я новичок в Java и Android и имею вопрос о получении ответа от сервера.У меня есть следующий код, который будет отправлять данные на сервер, но я хотел знать, должен ли этот код возвращать ответ.Если да, то как мне получить доступ к ответу:

public class SendPostRequest extends AsyncTask<String, Void, String> {

@Override
protected String doInBackground(String... params) {

    StringBuilder postData = new StringBuilder();

    HttpURLConnection httpConnection= null;
    try {

        httpConnection = (HttpURLConnection) new URL(params[0]).openConnection();
        httpConnection.setRequestMethod("POST");
        httpConnection.setDoOutput(true);

        DataOutputStream outputStream= new DataOutputStream(httpConnection.getOutputStream());
        outputStream.writeBytes(params[1]);
        outputStream.flush();
        outputStream.close();

        InputStream in = httpConnection.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(in);

        int inputStreamData = inputStreamReader.read();
        while (inputStreamData != -1) {
            char currentData = (char) inputStreamData;
            inputStreamData = inputStreamReader.read();
            postData.append(currentData);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (httpConnection!= null) {
            httpConnection.disconnect();
        }
    }
    return postData.toString();
}

  @Override
  protected void onPostExecute(String result) {
      super.onPostExecute(result);
  }
}

В MainActivity у меня есть:

public void signIn(View arg0)
{
    // Get text from email and password field
    final String email = etEmail.getText().toString();
    final String password = etPassword.getText().toString();
    JSONObject login = new JSONObject();
    try {
        login.put("email", email);
        login.put("password",password);


        new SendPostRequest().execute("https://example.com/API/test.php", login.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

Любая помощь в получении ответа сервера будет принята с благодарностью!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...