0

Использую HttpUrlConnection для связи с сервером.

        InputStream is = null;
        String parammetrs =  "clientId=" + client.getId() + "&bikeId=" + 1;
        BufferedReader br = null;
        String json = null;
        try {
            URL url = new URL(myURL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            connection.getOutputStream().write(parammetrs.getBytes("UTF-8"));
            is = connection.getInputStream();
            br = new BufferedReader(new InputStreamReader(is));
            json = (br.readLine().toString()); 
           } catch (MalformedURLException e) {
            e.printStackTrace();

        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();

        }

        return json;
    }

OnPostExecute у меня пока пустой.Как из сервера получить ответы типа boolean, ошибки(402,...) ?

4
  • Уточните, пожалуйста, что значит "ответ типа boolean"? В каком формате сервер отвечает (xml/json/html)?
    – andrikeev
    30 июн 2017 в 8:05
  • Вот так ошибки HTTP проверяются: ru.stackoverflow.com/questions/169762/… 30 июн 2017 в 8:12
  • @v.andrikeev Если отправленные данные верные , то сервер возвращает true, если нет , то - false. Там просто выходит true или false. Думаю что json. Другие данные в формате json скачиваю.
    – cherry
    30 июн 2017 в 8:52
  • @cherry добавьте в вопрос пример ответа от сервера. Если это json, должно быть что-то типа { "response": true }
    – andrikeev
    30 июн 2017 в 9:45

1 ответ 1

1

Пример для json ответа в виде { "response": true }

boolean getResponse() {
    String myURL = ...
    String parameters = "clientId=" + client.getId() + "&bikeId=" + 1;;
    HttpURLConnection connection = null;
    OutputStream outputStream = null;
    try {
        URL url = new URL(myURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
        outputStream = connection.getOutputStream();
        outputStream.write(parameters.getBytes("UTF-8"));

        int code = connection.getResponseCode();
        switch (code) {
            case 200:
                InputStream inputStream = connection.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader, 1024);
                StringBuilder stringBuilder = new StringBuilder();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                bufferedReader.close();

                String jsonResponse = stringBuilder.toString();
                try {

                    JSONObject jsonObject = new JSONObject(jsonResponse);
                    return jsonObject.getBoolean("response");

                } catch (JSONException e) {
                    Log.e(TAG, String.format("Error while deserializing response %s", jsonResponse));
                    return false;
                }

            case 402:
                // обработка ошибки
                return false;

            default:
                // обработка других возможных ошибок
                return false;
        }
    } catch (MalformedURLException e) {
        Log.e(TAG, String.format("Malformed url: %s", myURL));
        return false;
    } catch (IOException e) {
        Log.e(TAG, "Error while read/write");
        return false;
    } finally {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                Log.e(TAG, "Error while closing output stream");
            }
        }

        if (connection != null) {
            connection.disconnect();
        }
    }
}

Есть очень полезная библиотека OkHttp : http://square.github.io/okhttp/

которая значительно упрощает работу с сетевыми запросами. Например в вашем случае это будет выглядеть так:

boolean getResponse2() {
    OkHttpClient okHttp = new OkHttpClient.Builder()
            // Тут можно задать дополнительные настройки, например
            //.connectTimeout(5, TimeUnit.SECONDS) // таймауты
            //.readTimeout(5, TimeUnit.SECONDS)
            //.writeTimeout(5, TimeUnit.SECONDS)
            //.retryOnConnectionFailure(true) // повторная попытка при ошибке
            //.cache(new Cache(context.getCacheDir())) // кэширование ответа
            .build();

    HttpUrl url = new HttpUrl.Builder()
            .scheme("http")
            .host("example.com")
            .addPathSegment("path")
            .addPathSegment("to")
            .addPathSegment("resource")
            // Тут можно добавить параметры GET - запроса, например
            //.addQueryParameter("clientId", client.getId())
            //.addQueryParameter("bikeId", 1)
            .build(); // --> http://example.com/path/to/resource

    // Для POST-запроса нужно отдельно тело запроса создать
    RequestBody requestBody = new FormBody.Builder()
            .add("clientId", client.getId())
            .add(("bikeId"), 1)
            .build();

    Request request = new Request.Builder()
            .url(url)
            .post(requestBody)
            .build();

    try {
        Response response = okHttp.newCall(request).execute();
        String jsonResponse = response.body().string();
        try {

            JSONObject jsonObject = new JSONObject(jsonResponse);
            return jsonObject.getBoolean("response");

        } catch (JSONException e) {
            Log.e(TAG, String.format("Error while deserializing response %s", jsonResponse));
            return false;
        }

    } catch (IOException e) {
        Log.e(TAG, "Error while read/write");
        return false;
    }
}
1
  • спасибо за столь подробный ответ. Очень помогло. Благодарю.
    – cherry
    5 июл 2017 в 10:53

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.