RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 685512
Accepted
cherry
cherry
Asked:2020-06-30 16:03:10 +0000 UTC2020-06-30 16:03:10 +0000 UTC 2020-06-30 16:03:10 +0000 UTC

如何从服务器获取布尔类型的响应,errors(402,...)?Android HttpUrlConnection

  • 772

我正在使用 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 对我来说仍然是空的。如何从服务器获取布尔响应、错误 (402, ...)?

android
  • 1 1 个回答
  • 10 Views

1 个回答

  • Voted
  1. Best Answer
    andrikeev
    2020-06-30T18:32:14Z2020-06-30T18:32:14Z

    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

相关问题

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    Python 3.6 - 安装 MySQL (Windows)

    • 1 个回答
  • Marko Smith

    C++ 编写程序“计算单个岛屿”。填充一个二维数组 12x12 0 和 1

    • 2 个回答
  • Marko Smith

    返回指针的函数

    • 1 个回答
  • Marko Smith

    我使用 django 管理面板添加图像,但它没有显示

    • 1 个回答
  • Marko Smith

    这些条目是什么意思,它们的完整等效项是什么样的

    • 2 个回答
  • Marko Smith

    浏览器仍然缓存文件数据

    • 1 个回答
  • Marko Smith

    在 Excel VBA 中激活工作表的问题

    • 3 个回答
  • Marko Smith

    为什么内置类型中包含复数而小数不包含?

    • 2 个回答
  • Marko Smith

    获得唯一途径

    • 3 个回答
  • Marko Smith

    告诉我一个像幻灯片一样创建滚动的库

    • 1 个回答
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Алексей Шиманский 如何以及通过什么方式来查找 Javascript 代码中的错误? 2020-08-03 00:21:37 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    user207618 Codegolf——组合选择算法的实现 2020-10-23 18:46:29 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5