如何在Android中将JSON ARRAY数据发布到服务器

时间:2014-03-10 19:09:42

标签: android json getjson

我想将以下JSON数据发送到服务器并在android中读取响应。 以下是Json数据。

{
    "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"
        }
    ]
}

这里可能会增加数据。

3 个答案:

答案 0 :(得分:7)

检查此代码

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

答案 1 :(得分:2)

Android没有用于发送和接收HTTP的特殊代码,您可以使用标准Java代码。我建议使用Android附带的Apache HTTP客户端。这是我用来发送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 :(得分:0)

您也可以使用WebClient类以字符串形式将Json发送到服务器。

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;