0

我有一个返回 json 响应的 web 服务,json 响应包含纯文本和 base64 编码的图像,我正在使用 android 应用程序使用该服务,所以我实现了进度条来指示进度。

实现进度条迫使我使用 BufferedInputStream 来读取响应并根据应用程序正在读取的内容更新进度。

问题是一切正常并且进度更新正确,但是在收集响应并退出 while 循环后,我尝试使用 JSONObject 将字符串转换为 json 格式。这是代码片段

BufferedInputStream bis = new BufferedInputStream(responseEntity.getContent());
            StringBuilder sb = new StringBuilder();
            String line = null;
            int total = 0 ;
            int count = 0 ;
            byte[] buffer = new byte[4096];
            StringBuffer sBuffer = new StringBuffer();
            StringWriter sw = new StringWriter();
            String content = new String();

            while((count = bis.read(buffer)) > 0){
                content += new String(buffer,Charset.defaultCharset());

                total += count;
                publishProgress(""+(int )total*100/this.contentSize);
                Log.i("updating",""+(int )total*100/this.contentSize);
            }


            bis.close();
           // String content = new String(sb);
            // Log.i("ServerRawresponse",content);
            try {
                Log.i("REsponse_Content",content.replaceAll("\"", ""));
                responseString = new JSONObject(new JSONTokener(content.replaceAll("\"", "\\\"")));
                //System.out.println(content);
            } catch (JSONException e) {
                e.printStackTrace();

            }

请提供任何帮助

4

1 回答 1

1

试试这个方法对我很有效

HttpResponse WSresponse = httpclient.execute(httppost);
String response = getResponseBody(WSresponse.getEntity());
JSONObject jobj = new JSONObject(response);

public String getResponseBody(final HttpEntity entity) throws IOException, ParseException {

        System.out.println("GEN START : " + Calendar.getInstance().getTimeInMillis());
        if (entity == null) {
            throw new IllegalArgumentException("HTTP entity may not be null");
        }

        InputStream instream = entity.getContent();

        if (instream == null) {
            return "";
        }

        if (entity.getContentLength() > Integer.MAX_VALUE) {
            throw new IllegalArgumentException(

            "HTTP entity too large to be buffered in memory");
        }


        StringBuilder buffer = new StringBuilder();

        BufferedReader reader = new BufferedReader(new InputStreamReader(instream, HTTP.UTF_8));

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

        } finally {
            instream.close();
            reader.close();
        }

        return buffer.toString();

    }
于 2013-08-26T06:56:00.780 回答