How to send JSON ARRAY data to a server in Android

I want to send the JSON data below to the server and read the response in android. Following are the Json data.

{ "class": "OrderItemListDto", "orderItemList": [ { "class": "OrderItemDto", "orderId": 24, "itemId": 1, "quantity": 2, "status": "NEW", "sRequest": "none" }, { "class": "OrderItemDto", "orderId": 24, "itemId": 2, "quantity": 2, "status": "NEW", "sRequest": "none" } ] } 

Here the data can be enlarged.

+7
json android getjson
source share
3 answers

Check this code

 JSONArray json = //your array; HttpClient httpClient = new DefaultHttpClient(); HttpContext httpContext = new BasicHttpContext(); HttpPost httpPost = new HttpPost("http://your_url"); try { StringEntity se = new StringEntity(json.toString()); httpPost.setEntity(se); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json"); HttpResponse response = httpClient.execute(httpPost, httpContext); //execute your request and parse response HttpEntity entity = response.getEntity(); String jsonString = EntityUtils.toString(entity); //if response in JSON format } catch (Exception e) { e.printStackTrace(); } 
+7
source share

Android does not have a special code for sending and receiving HTTP, you can use standard Java code. I would recommend using the Apache HTTP client that comes with Android. Here is the code snippet that I used to send the HTTP POST.

 try { int TIMEOUT_MILLISEC = 10000; // = 10 seconds HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC); HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC); HttpClient client =new DefaultHttpClient(httpParams); HttpPost request =new HttpPost(""); request.setEntity(new ByteArrayEntity(postMessage.toString().getBytes("UTF8"))); HttpResponse response = client.execute(request); }catch (Exception e) { } 
+2
source share

You can also send Json in string form to the server using the WebClient class.

 WebClient webClient; //show progress dialog Uri uriImageUploadURL = new Uri ( "ServerStringUploadUri" ); webClient = webClient ?? new WebClient (); webClient.Headers.Add ( "Content-Type" , "text/json" ); webClient.UploadStringAsync ( uriImageUploadURL , "POST" , "JsonStringToUpload" ); webClient.UploadStringCompleted += StringUploadCompleted; 
0
source share

All Articles