android - 从字符串创建json对象来处理网络错误

时间:2015-08-21 15:58:44

标签: java android json

我需要创建json对象来处理网络调用错误

我解析错误的方式

{error:errorMessage}

我的尝试:

 String error = "{\"error\":\""+ e.getMessage()+"\"}";

但是当我转换jsonObject = new JSONObject(stringBuilder.toString());

它抛出异常

我的代码

public class HttpBackground implements Runnable {
        HttpDefs client;
        String error = null;
        JSONObject jsonObject;

        public HttpBackground(HttpDefs client) {
            this.client = client;
        }

        @Override
        public void run() {
            final StringBuilder stringBuilder = new StringBuilder();
            String line = null;
            BufferedReader reader = null;

            try {

                HttpURLConnection connection = (HttpURLConnection) client._url.openConnection();
                connection.setRequestMethod(client.Request_type);
                connection.setReadTimeout(AppStaticMembers.WAIT_RESPONSE_TIMEOUT);

                OutputStream outputStream = connection.getOutputStream();
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                writer.write(getQuery(client.params));
                writer.flush();
                writer.close();
                outputStream.close();
                connection.connect();
                if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

                } else {
                    reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
                }
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }


            } catch (SocketTimeoutException e) {
                error = "{\"error\":\""+ e.getMessage()+"\"}";

            } catch (Exception e) {
                e.printStackTrace();
                error = "{\"error\":\""+ e.getMessage()+"\"}";
            } finally {
                if (reader != null) {

                    try {
                        reader.close();


                        stringBuilder.append(error);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            try {
                jsonObject = new JSONObject(stringBuilder.toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }


            httpUI httpUI = new httpUI(jsonObject, this.client);
            handler.post(httpUI);
        }

    }

0 个答案:

没有答案