0
在我的应用程序中,我将图像转换为bas64字符串并将其添加到JSON对象以发送到服务器。问题似乎是字符串太大了?最初我得到了一个内存不足的错误,现在响应只是返回null,并且我调试了它,直到我发现它传递给我的StringEntity对象的字符串太大。我已经阅读了很多其他答案,但都没有工作,或者他们只是不太适用于我需要做的事情。该代码如下JSON字符串对于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\"}]}");
工作得很好
任何想法,将不胜感激
有很好的链接InputStreamEntity? – KBusc
和任何想法这将如何改变我的后端?有什么我需要在那里改变 – KBusc
为什么不使用FileEntity?图像可能非常大,在将图像转换为json时,应该以流方式进行,并将结果存储在文件中,不要将所有数据加载到内存中,否则OOM错误会在大多数意想不到的时刻不时出现。 – marcinj