how to post JSON ARRAY data to server in Android

安稳与你 提交于 2019-12-09 17:46:20

问题


I want to send below JSON data to server and read the response in android. Below is 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 May be data will be increased.


回答1:


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



回答2:


Android doesn't have special code for sending and receiving HTTP, you can use standard Java code. I'd recommend using the Apache HTTP client, which comes with Android. Here's a snippet of code I used to send an 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) {        
        }



回答3:


You can also send Json in string form to server using 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;


来源:https://stackoverflow.com/questions/22309127/how-to-post-json-array-data-to-server-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!