2016-03-02 110 views
0

我正在使用HttpClient 4.3.6執行http GET和POST請求。現在我正在使用multipartentity以文件的形式發送一些字符串參數和圖像。我能夠成功發佈數據,但是當我收到HTTP響應時,我的問題就出現了。該響應包含json數據。Android Http響應不完整。返回未終止的json對象

會發生什麼事是HTTP響應不完整的,當我嘗試創建與數據JSON對象,我得到jsonexception錯誤說:

在字符未終止的對象407

我注意到該響應不包含閉括號。這是一個問題在android或我應該檢查服務器?因爲我能夠在郵差和ios上正確查看數據。我從來沒有面對過這個問題,也不知道如何解決這個問題。

這是我的代碼來發布和獲取響應:

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

    try { 
     String url = params[0]; 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost(url); 
     MultipartEntity entity = new MultipartEntity(); 
     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
     bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); 
     byte[] imageBytes = baos.toByteArray(); 
     ByteArrayBody bab = new ByteArrayBody(imageBytes, "image.jpg"); 
     entity.addPart("image_data", bab); 
     entity.addPart("action", new StringBody("1", "text/plain", Charset.forName("UTF-8"))); 
     entity.addPart("name", new StringBody("asdfg", "text/plain", Charset.forName("UTF-8"))); 
     entity.addPart("user_id", new StringBody("157", "text/plain", Charset.forName("UTF-8"))); 
     entity.addPart("birthday", new StringBody("18-04-1995", "text/plain", Charset.forName("UTF-8"))); 
     entity.addPart("gender", new StringBody("male", "text/plain", Charset.forName("UTF-8"))); 
     entity.addPart("is_jlpt_student", new StringBody(String.valueOf(0), "text/plain", Charset.forName("UTF-8"))); 
     entity.addPart("relationship", new StringBody("Father", "text/plain", Charset.forName("UTF-8"))); 
     entity.addPart("relationship_id", new StringBody(String.valueOf(10002), "text/plain", Charset.forName("UTF-8"))); 
     entity.addPart("is_creator", new StringBody(String.valueOf(1), "text/plain", Charset.forName("UTF-8"))); 
     entity.addPart("email", new StringBody(email, "text/plain", Charset.forName("UTF-8"))); 

     httppost.setEntity(entity); 
     HttpResponse resp = httpclient.execute(httppost); 
     String response = EntityUtils.toString(resp.getEntity()); 
     Log.i("HttpResponse", response); 

     return response; 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    return null; 

} 

@Override 
protected void onPostExecute (String result) { 
    super.onPostExecute(result); 

    JSONObject jsonObject = null; 
    try { 
     jsonObject = new JSONObject(result); 
     JSONObject json_data = jsonObject.getJSONObject("data"); 
     String json_userid = json_data.getString("user_id"); 
     String json_username = json_data.getString("name"); 
     String json_email = json_data.getString("email"); 
     String json_country = json_data.getString("country_code"); 
     String json_imagefilename = json_data.getString("image_filename"); 
     String json_imgurl = json_data.getString("image_url"); 

     Toast.makeText(ParentGuardianProfile.this, "ImageFile " + json_imagefilename, Toast.LENGTH_SHORT).show(); 


     User new_user = userdao.createUser(json_userid, json_username, json_email,json_imagefilename,json_country,selectedImageUri.toString(), 1); 


     Log.i("SQLITE", "added user : " + new_user.getmUserName() + new_user.getmId()); 


    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
}        

我的JSON的迴應是:

{"status":1,"message":"success","data":{"child_id":"381","name":"asdfg","image_filename":"C201603021734476.jpg","image_url":"https:\/\/innokid.blob.core.windows.net\/media\/child\/381.jpg","birthday":"18-04-1995","gender":"male","is_jltp_student":"0","relationship":"Father","relationship_id":"10002","is_creator":1,"rank":1,"qrcode_url":"http:\/\/innokid.azurewebsites.net\/uploads\/qrcode\/child_381.png" 

我嘗試使用字符串緩衝區這篇文章String is being truncated when its too long建議。但我仍然得到相同的結果。

+0

它是你的完整json響應? –

+0

請檢查服務器代碼,通過它的編碼爲JSON正確 –

回答

0

代碼看起來很好乍一看。 你怎麼知道json數據被切斷? Logcat可以截斷文本。在這種情況下調試器應該更可靠。

嘗試使用curl/SoapUI等工具生成相同的請求,並使用某些格式化程序/驗證程序(您可以輕鬆找到一些此類工具)驗證JSON。

它超出了問題的範圍,但使用原始的Android內置通信庫似乎有點受虐狂。你有沒有考慮過使用Retrofit?

+0

我檢查在調試器響應字符串。它不具備的JSONObject – nexus

+0

的結束括號所以我的建議是檢查什麼服務器與一些獨立的工具 – piotrpo

+0

回來時,我檢查了郵差和反應似乎properly.No字符被錯過 – nexus

0

我覺得這個代碼是有問題的String response = EntityUtils.toString(resp.getEntity());

可能是你應該使用一些其他的功能轉換響應的toString ...

顯然,JSON是缺少兩個花括號末「}}」,這可能由於toString代碼中的一些錯誤而發生。

0

我拉起了一個使用org.apache.http東西的舊項目,下面是我如何解析響應。正如你所看到的那樣很麻煩。在那裏有很多經過測試和維護的庫,更適合這種繁重的工作。

// Get hold of the response entity (-> the data): 
HttpEntity entity = response.getEntity(); 

if (entity != null) { 
    // Read the content stream 
    InputStream instream = entity.getContent(); 
    Header contentEncoding = response.getFirstHeader("Content-Encoding"); 
    if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { 
     instream = new GZIPInputStream(instream); 
    } 

    // Convert content stream to a String 
    resultString = convertStreamToString(instream); 
    instream.close(); 

    // Do stuff with resultString here 

    // Consume Content 
    entity.consumeContent(); 

} 

而且convertStreamToString()方法:

private static String convertStreamToString(InputStream is) { 
     /* 
     * To convert the InputStream to String we use the 
     * BufferedReader.readLine() method. We iterate until the BufferedReader 
     * return null which means there's no more data to read. Each line will 
     * appended to a StringBuilder and returned as String. 
     * 
     * (c) public domain: 
     * http://senior.ceng.metu.edu.tr/2009/praeda/2009/01/ 
     * 11/a-simple-restful-client-at-android/ 
     */ 
     BufferedReader reader = new BufferedReader(new InputStreamReader(is), 8192); 
     StringBuilder sb = new StringBuilder(); 

     String line = null; 
     try { 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       is.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
     return sb.toString(); 
    } 
0

我終於通過了Android異步HTTP客戶端替換HttpClient庫解決了這個問題。現在它工作正常。非常感謝你的幫助! 但是,我仍然不明白爲什麼我使用httpclient時截斷了響應。