对于StringEntity,JSON字符串太大

时间:2014-01-09 13:55:03

标签: android json android-asynctask string-length android-memory

在我的应用程序中,我将图像转换为bas64字符串,并将其添加到JSON对象以发送到服务器。问题似乎是字符串太大了?最初我得到了一个内存不足错误,现在响应只返回null并且我调试它到我发现它的字符串我传递给我的StringEntity对象太大了。我已经阅读了很多其他答案,但没有一个有效,或者它们不适用于我需要做的事情。守则如下

@Override
    protected String doInBackground(JSONArray... params) {

        JSONObject allPostObj = new JSONObject();
        try {

            allPostObj.put("receiptImgs", params[0]);

            //Log.e("in obj Try" , allPostObj.toString());

            DefaultHttpClient httpClient = new DefaultHttpClient(); 
            // WCF service path
            HttpPost httpPost = new HttpPost("http://localhost/path");
            HttpParams httpParameters = new BasicHttpParams();
            // Set the timeout in milliseconds until a connection is established.
            // The default value is zero, that means the timeout is not used.
            int timeoutConnection = 10000;
            HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
            // Set the default socket timeout (SO_TIMEOUT)
            // in milliseconds which is the timeout for waiting for data.
            int timeoutSocket = 10000;
            HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
            httpPost.setParams(httpParameters);
            StringEntity se = new StringEntity(allPostObj.toString());
            Log.e("DEBUGGING",allPostObj.toString());
            se.setContentType("application/json;charset=UTF-8");                 
            httpPost.setEntity(se);

            HttpResponse httpResponse = httpClient.execute(httpPost);         
            HttpEntity httpEntity = httpResponse.getEntity(); 

            BufferedReader reader = new BufferedReader(new InputStreamReader(httpEntity.getContent()));
            String readLine = reader.readLine();
            Log.d("DEBUG RESPONSE",readLine);
            JSONObject jsonResponse = new JSONObject(readLine);

            answer = jsonResponse.getString("saveImageResult");
            Log.e("returning", answer);
        }

并替换

StringEntity se = new StringEntity(allPostObj.toString());

使用:

StringEntity se = new StringEntity("{\"receiptImgs\":[{\"imgString\":\"\",\"imgPath\":\"test\"}]}");

工作得很好

任何想法都将受到高度赞赏

1 个答案:

答案 0 :(得分:1)

您不应将StringEntity用于大型内容,您应切换到FileEntityInputStreamEntity,具体取决于您存储数据的位置。


快速修复你可以尝试(没有编译/测试):

InputStream stream = new ByteArrayInputStream(allPostObj.toString().getBytes("UTF-8"));
InputStreamEntity entity = new InputStreamEntity(stream , -1);