Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to POST data in Android to server in JSON format?

I have this JSON string. I want to POST it to the server (i.e. using the POST method). How can this be done in Android?

JSON string:

{
    "clientId": "ID:1234-1234",
    "device": {
        "userAgent": "myUA",
        "capabilities": {
            "sms": true,
            "data": true,
            "gps": true,
            "keyValue": {
                "Key2": "MyValue2",
                "Key1": "myvalue1"
            }
        },
        "screen": {
            "width": 45,
            "height": 32
        },
        "keyValue": {
            "DevcKey2": "myValue2",
            "DevcKey1": "myValue1"
        }
    },
    "time": 1294617435368
}

How can I form this JSON array and POST it to the server?

like image 534
N-JOY Avatar asked Feb 11 '11 06:02

N-JOY


People also ask

How do I post JSON to the server?

Use JSON. stringify() to convert the JavaScript object into a JSON string. Send the URL-encoded JSON string to the server as part of the HTTP Request. This can be done using the HEAD, GET, or POST method by assigning the JSON string to a variable.

How can post form data in JSON server?

Using the JSON. stringify() method then format the plain form data as JSON. Specify the HTTP request method as POST and using the header field of the Fetch API specify that you are sending a JSON body request and accepting JSON responses back. Then set the request body as JSON created from the form fields.

How do I post to JSON?

POST requestsIn Postman, change the method next to the URL to 'POST', and under the 'Body' tab choose the 'raw' radio button and then 'JSON (application/json)' from the drop down. You can now type in the JSON you want to send along with the POST request. If this is successful, you should see the new data in your 'db.

How do I pass JSON payload?

To send the JSON with payload to the REST API endpoint, you need to enclose the JSON data in the body of the HTTP request and indicate the data type of the request body with the "Content-Type: application/json" request header.


3 Answers

I did it myself.

JSONObject returnedJObject= new JSONObject();
JSONObject KeyvalspairJObject=new JSONObject ();
JSONObject devcKeyvalspairJObject=new JSONObject ();
JSONObject capabilityJObject=new JSONObject();
JSONObject ScreenDimensionsJObject =new JSONObject();
JSONObject deviceJObject= new JSONObject();
try{
    KeyvalspairJObject.put("key1","val1");
    KeyvalspairJObject.put("key2","val2");
    capabilityJObject.put("sms", false);
    capabilityJObject.put("data", true);
    capabilityJObject.put("gps", true);
    capabilityJObject.put("wifi", true);
    capabilityJObject.put("keyValue", KeyvalspairJObject);
    ScreenDimensionsJObject.put("width", 45);
    ScreenDimensionsJObject.put("height", 45);
    devcKeyvalspairJObject.put("Devckey1","val1");
    devcKeyvalspairJObject.put("DEVCkey2","val2");
    deviceJObject.put("userAgent", "MYUserAgent");
    deviceJObject.put("capabilities", capabilityJObject);
    deviceJObject.put("screen", ScreenDimensionsJObject);
    deviceJObject.put("keyValue", devcKeyvalspairJObject);

    returnedJObject.put("clientId", "ID:1234-1234");
    returnedJObject.put("carrier","TMobile");
    returnedJObject.put("device",deviceJObject);
    returnedJObject.put("time",1294617435);
    returnedJObject.put("msisdn","1234567890");
    returnedJObject.put("timezone","GMT");
}
catch(JSONException e)
{
}

and this is how we can send JSON data to server.

public String putDataToServer(String url,JSONObject returnedJObject) throws Throwable
{
    HttpPost request = new HttpPost(url);
    JSONStringer json = new JSONStringer();
    StringBuilder sb=new StringBuilder();


    if (returnedJObject!=null) 
    {
        Iterator<String> itKeys = returnedJObject.keys();
        if(itKeys.hasNext())
            json.object();
        while (itKeys.hasNext()) 
        {
            String k=itKeys.next();
            json.key(k).value(returnedJObject.get(k));
            Log.e("keys "+k,"value "+returnedJObject.get(k).toString());
        }             
    }
    json.endObject();


    StringEntity entity = new StringEntity(json.toString());
                         entity.setContentType("application/json;charset=UTF-8");
    entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
    request.setHeader("Accept", "application/json");
    request.setEntity(entity); 

    HttpResponse response =null;
    DefaultHttpClient httpClient = new DefaultHttpClient();

    HttpConnectionParams.setSoTimeout(httpClient.getParams(), Constants.ANDROID_CONNECTION_TIMEOUT*1000); 
    HttpConnectionParams.setConnectionTimeout(httpClient.getParams(),Constants.ANDROID_CONNECTION_TIMEOUT*1000); 
    try{
        response = httpClient.execute(request); 
    }
    catch(SocketException se)
    {
        Log.e("SocketException", se+"");
        throw se;
    }
    InputStream in = response.getEntity().getContent();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    String line = null;
    while((line = reader.readLine()) != null){
        sb.append(line);
    }
    return sb.toString();
}
like image 100
N-JOY Avatar answered Nov 02 '22 10:11

N-JOY


If you have JSON as String already, just POST it using regular HTTP connection (URL.openConnection()). No need to parse it or anything like that.

like image 36
StaxMan Avatar answered Nov 02 '22 09:11

StaxMan


Have a look at this code

https://gist.github.com/9457c486af9644cf6b18

See the retrieveJSONArray(ArrayList jsonArray,String[] key) and retrieveJSONString(ArrayList jsonObject)

like image 21
viv Avatar answered Nov 02 '22 08:11

viv