问题描述:

In my app I turn an image into a bas64 string and add it to a JSON object to send to the server. The problem seems to be that the string is too large? Originally I was getting an out of Memory error now the response just returns null and Ive debugged it to the point where I have found it to be that the String I pass to my StringEntity Object is too large. I have read alot of other answers but none have worked or they just don't quite apply to what I need to do. The Code is as follows

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

}

And replacing the line

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

With:

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

Works just fine

Any ideas will be greatly appreciated

网友答案:

You should not use StringEntity for large content, you should switch to FileEntity or InputStreamEntity, depending on where you store your data.


quick fix you may try (not compiled/tested):

InputStream stream = new ByteArrayInputStream(allPostObj.toString().getBytes("UTF-8"));
InputStreamEntity entity = new InputStreamEntity(stream , -1);
相关阅读:
Top