1

I have a JSON array, which further consist of many JSON object and I want to post this JSON array on http post connection as a string. My problem is that when I convert the JSON array to string then string variable holds only subset of JSON array data(due to size limit of String variable). As I result I post incomplete JSON array. what is the solution to post large JSON array on the http connection. Below code convert JSON array to String.

JSONArray jsonArray = new JSONArray();
jsonArray .toString();
mkj
  • 2,761
  • 5
  • 24
  • 28
user3586231
  • 391
  • 4
  • 21

1 Answers1

2

Use HttpURLConnection ( http://developer.android.com/reference/java/net/HttpURLConnection.html) Developer docs clearly say that

An URLConnection for HTTP (RFC 2616) used to send and receive data over the web. Data may be of any type and length. This class may be used to send and receive streaming data whose length is not known in advance.

Sample code to post a query :

HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
 urlConnection.setDoOutput(true);
 urlConnection.setChunkedStreamingMode(0);

 OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
 writeStream(out); // read data from db and write it to stream

 InputStream in = new BufferedInputStream(urlConnection.getInputStream());
 readStream(in);
finally {
 urlConnection.disconnect();
}
}

writeStream(OutputStream out) {
  while (read all records from db) {
     byte[] bytes = record.getBytes("UTF-8");
     out.write(bytes);
  }
}

Use the above code inside an AsycTask doInBackground method. Read all the records from database and add to to outputstream inside the function writeStream. Using this method, your string variable will only contain one record at any time.

droidmad
  • 807
  • 7
  • 13
  • problem is how to convert Json Array to a stream, because String variable holds data upto certain limit. – user3586231 Dec 17 '14 at 08:21
  • 1
    It's not the String which has a limited size (unless of course it's bigger than the max int size which is (2^31 - 1) ) but there's a limit to the amount of data that you can pass through the HTTP POST. – Shivam Verma Dec 17 '14 at 08:49
  • 1
    The trick is to read a record from db and immediately write it to the stream (because we cannot store entire data in a string). – droidmad Dec 17 '14 at 08:52
  • @ShivamVerma . What you are saying might be true but generally that limit will be set on server side. For Apache Tomcat, see this link http://stackoverflow.com/questions/2943477/is-there-a-max-size-for-post-parameter-content – droidmad Dec 17 '14 at 08:59