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\"}]}"); 

工作得很好

任何想法,將不勝感激

回答

1

你壽ld對於大型內容不使用StringEntity,您應該切換到FileEntityInputStreamEntity,這取決於您存儲數據的位置。


速戰速決,你可以嘗試(不編譯/測試):

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

有很好的鏈接InputStreamEntity? – KBusc

+0

和任何想法這將如何改變我的後端?有什麼我需要在那裏改變 – KBusc

+0

爲什麼不使用FileEntity?圖像可能非常大,在將圖像轉換爲json時,應該以流方式進行,並將結果存儲在文件中,不要將所有數據加載到內存中,否則OOM錯誤會在大多數意想不到的時刻不時出現。 – marcinj

相關問題