2016-01-23 113 views
1

我想發送數據作爲字符串從api應用程序的api,但是當我以字符串形式發送大量數據時,它顯示我這個錯誤「java.net.ProtocolException:內容長度承諾16280字節,但收到16272」。如果我發送少量的數據,它不會給出任何錯誤。它說有關內容長度不匹配,我沒有得到它。java.net.ProtocolException:內容長度承諾16280字節,但收到16272

我分享你我的代碼,請

enter code here 

private class AsyncTaskRunner extends AsyncTask<Void, 
Void, ArrayList<String[]>> { 

    private String resp; 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 

     progressBar = new ProgressDialog(getActivity()); 
     progressBar.setCancelable(true); 
     progressBar.setMessage("Fetching Contacts ..."); 
     progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER); 
     progressBar.show(); 
    } 

    @Override 
    protected ArrayList<String[]> doInBackground(Void... params) { 


     ContentResolver cr = getActivity().getContentResolver(); 
     Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, 
       null, null, null, null); 
//  ArrayList<String[]> contacts = new ArrayList<String[]>(); 
     if (cur.getCount() > 0) { 
      while (cur.moveToNext()) { 
     String id =cur.getString(cur.getColumnIndex 
(ContactsContract.Contacts._ID)); 
       String name = cur.getString(cur.getColumnIndex 
(ContactsContract.Contacts.DISPLAY_NAME)); 

       String phones = null; 
       if (Integer.parseInt(cur.getString(cur.getColumnIndex 
(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) { 
        //Query phone here. Covered next 
        if (Integer.parseInt(cur.getString(cur.getColumnIndex 
    (ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) { 
         Cursor pCur = cr.query(
           ContactsContract.CommonDataKinds.Phone. 
    CONTENT_URI,null, 
           ContactsContract.CommonDataKinds. 
    Phone.CONTACT_ID + " = ?", 
           new String[]{id}, null); 
         while (pCur.moveToNext()) { 
          // Do something with phones 
          phones = pCur.getString(pCur.getColumnIndex 
    (ContactsContract.CommonDataKinds.Phone.NUMBER)); 
    //       String[] str = new String[3]; 
    //       str[0] = id; 
    //       str[1] = name; 
    //       str[2] = phones; 
    //       contacts.add(str); 

         } 
         pCur.close(); 
        } 
       } 
       String[] str = new String[3]; 
       str[0] = id; 
       str[1] = name; 
       str[2] = phones; 
       long val1 = adapter1.insertContacts(id, name, phones); 
       JSONObject jsonObject = new JSONObject(); 
       try { 
        jsonObject.put("name", name); 
        jsonObject.put("phones", phones); 
        jsonArray.put(jsonObject); 


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

       Log.d("value is", "" + val1); 
       contacts.add(str); 

      } 
     } 
     cur.close(); 
     String name = "Siddhant"; 
     String postjson = String.valueOf(jsonArray); 
     rsp = serviceResponse(postjson, Config.URL_SAVE_CONTACTS); 

     Collections.sort(contacts, ALPHABETICAL_ORDER); 
     mAllData.addAll(contacts); 

     return contacts; 
    } 

    private Comparator<String[]> ALPHABETICAL_ORDER = 
    new Comparator<String[]>() 
    { 
     @Override 
     public int compare(String[] lhs, String[] rhs) { 
      int res = String.CASE_INSENSITIVE_ORDER.compare(lhs[1], rhs[1]); 
      if (res == 0) { 
       res = lhs[1].compareTo(rhs[1]); 
      } 
      return res; 
     } 
    }; 

    @Override 
    protected void onPostExecute(ArrayList<String[]> result) { 
     super.onPostExecute(result); 

     adapter = new ContactsListAdapter(getActivity(), contacts); 
     listView.setAdapter(adapter); 
     progressBar.dismiss(); 
     if (rsp!=null) { 
      String json = rsp.toString(); 
      Toast.makeText(getActivity(), json, Toast.LENGTH_SHORT).show(); 
     } 
    } 
    } 

    public String serviceResponse(String postStr, String urlString) { 

    HttpURLConnection connection = null; 
    try { 

    //   original code 
    // Create connection 
     URL url = new URL(urlString); 
     connection = (HttpURLConnection) url.openConnection(); 
     connection.setRequestMethod("POST"); 
     connection.setRequestProperty("Content-Type", 
    "application/x-www- form-urlencoded"); 
    // connection.setRequestProperty("Content-Type", "application/json"); 

     connection.setRequestProperty 
    ("Content-Length", "" +Integer.toString(postStr.getBytes().length)); 

     connection.setRequestProperty("Content-Language", "en-US"); 
     connection.setUseCaches(false); 
     connection.setDoOutput(false); 

    // Send request 
     DataOutputStream wr = 
    new DataOutputStream(connection.getOutputStream()); 

     wr.writeBytes(postStr); 
     wr.flush(); 
     wr.close(); 

     int status = connection.getResponseCode(); 
    // return String.valueOf(status); 

     InputStream is; 
     if (status >= HttpStatus.SC_BAD_REQUEST) 
      is = connection.getErrorStream(); 
     else 
      is = connection.getInputStream(); 
    // Get Response 
     BufferedReader rd = new BufferedReader(new InputStreamReader(is)); 
     String line; 

     StringBuffer response = new StringBuffer(); 
     while ((line = rd.readLine()) != null) { 

      response.append(line); 
     } 
     rd.close(); 
     return response.toString(); 


    } catch (Exception e) { 
     e.getMessage(); 
     return null; 

    } finally { 

     if (connection != null) { 
      connection.disconnect(); 
     } 
    } 
    } 

回答

5

,我認爲它是關於getBytes()

時一定要小心使用它,因爲你必須通過像.getBytes("UTF-8")

的字符編碼參數如果你沒有傳遞任何參數,它將使用系統默認值。

我的教育猜測是你的數據不是一個標準的UTF-8數據,所以你應該給出正確的字符集,我認爲之後你的數據長度將匹配。

編輯: 現在,我看到你的錯誤。

當您設置

wr.writeBytes(postStr); 

它設置錯誤再次編碼:) 你應該做這樣的事情:

wr.write(postStr.getBytes("UTF-8")); 

PS:你應該改變 「UTF-8」 以任何支持您的語言以正確地在服務器端獲取數據。

+0

感謝您的幫助Gunhan,我改變了它,但仍然錯誤是一樣的。 –

+0

如果你根本沒有設置內容長度會發生什麼? – Gunhan

+0

它仍然在發生,只是現在我檢查,如果我手動添加8個字節比它不給錯誤,但我不能在writebytes()手動添加更多的字節,所以我不知道該怎麼做。 –