使用JSON响应在Http REST服务上传输Base64字符串

时间:2013-08-26 06:40:10

标签: java android json http base64

我有一个返回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();

            }

请帮助

1 个答案:

答案 0 :(得分:0)

尝试使用此方法与我完美配合

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();

    }