java.net.ProtocolException:content-length承诺16280字节,但收到16272(java.net.ProtocolException: content-length promised 16280 bytes, but received 16272)

我想发送数据作为字符串从android应用程序的API,但是当我以字符串形式发送大量数据时,它显示我这个错误“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(); } } }

I want to send data as a string to an api from android app, but when I send large amount of data in string form it shows me this error "java.net.ProtocolException: content-length promised 16280 bytes, but received 16272" . And if I send small amount of data it don't give any error. Its saying something about content length mismatch and I am not getting it.

I am sharing you my code please check

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(); } } }

最满意答案

我认为这是关于getBytes()

使用它时要小心,因为必须传递像.getBytes("UTF-8")这样的字符编码参数

如果您没有传递任何参数,它将使用系统默认值。

我有根据的猜测是你的数据不是标准的UTF-8数据,所以你应该给出正确的字符集,我认为你的数据长度将匹配。

编辑:现在,我看到你的错误。

当你设置

wr.writeBytes(postStr);

它再次错误地设置编码:)你应该这样做:

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

ps:您应该将“UTF-8”更改为支持您的语言的任何内容,以便正确地在服务器端获取数据。

I think it is about getBytes()

Be careful when you use it because you have to pass the character encoding parameter like .getBytes("UTF-8")

If you don't pass any parameter it will use the system default.

My educated guess is that your data is not a standard UTF-8 data so you should give the correct character set and i think after that your data length will match.

Edit: Now, I see your mistake.

When you set

wr.writeBytes(postStr);

It sets the encoding wrongly again :) You should do something like that:

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

p.s: you should change "UTF-8" to anything that supports your language to get your data on the server side correctly.

更多推荐