17

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?

Pang
  • 9,564
  • 146
  • 81
  • 122
N-JOY
  • 10,344
  • 7
  • 51
  • 69
  • possible duplicate of [How do I send JSon as BODY In a POST request to server from an Android application?](http://stackoverflow.com/questions/3815522/how-do-i-send-json-as-body-in-a-post-request-to-server-from-an-android-applicatio) – Thilo Feb 11 '11 at 06:25
  • 1
    in org.json package (http://developer.android.com/reference/org/json/package-summary.html) it should have everything you need to construct JSON string. – xandy Feb 11 '11 at 06:26
  • @Thilo nop that does not have stuff about how 2 form json string.... – N-JOY Feb 11 '11 at 06:32
  • i want to add a jsonArray also in this what should i do, can you guide for this? – Bhunnu Baba Oct 18 '16 at 08:34

6 Answers6

17

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();
}
Pang
  • 9,564
  • 146
  • 81
  • 122
N-JOY
  • 10,344
  • 7
  • 51
  • 69
  • why is the jsonObj parameter in putData called returnedJObject? doesn't it represent the object that needs to be sent? Also for me it's not working I get "no input data" from the server with code 200 – Mihai Bratulescu Sep 18 '13 at 14:52
  • just to make below code in sync with above code i used returnedJObject. Using other name will not break the code ;). but thanks for pointing that out. And if you are receiving code 200 then it must be success response from server. 200 stands for "status ok". – N-JOY Sep 18 '13 at 17:58
  • yes but the response I get means the server didn't got any input, I'll try to talk to the guy working on the API (the problem must be there) but he didn't answered my emails today – Mihai Bratulescu Sep 18 '13 at 18:56
  • ya may be server guys can give you more insight on this. – N-JOY Sep 18 '13 at 19:03
8

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.

StaxMan
  • 113,358
  • 34
  • 211
  • 239
1
JSONObject returnedJObject= new JSONObject();

url = "http://49.50.76.75/website/exxx/api.php";

// makeSignupRequest();

try {
    returnedJObject.put("email",eemail);
    returnedJObject.put("password",passwrd);
    returnedJObject.put("type","customer");
    returnedJObject.put("method","register");
    returnedJObject.put("username",usr);

    try {
        putDataToServer(url, returnedJObject);

    }
    catch (Throwable m) {
        m.printStackTrace();
    }
}
Jonnus
  • 2,988
  • 2
  • 24
  • 33
1

Have a look at this code

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

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

Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110
viv
  • 6,158
  • 6
  • 39
  • 54
  • u wanted to create JSON string....... the basic logic is there in retrieveJSONString, but it is customized as per my logic and requirement....... – viv Feb 11 '11 at 07:01
0

IF this is anything other than a "Hobby" app with just one or two service calls to make, I'd consider looking at an async HTTP or REST library.

There are several worth consideration, including Volley from Google: https://developer.android.com/training/volley/index.html

and Retrofit from Square: http://square.github.io/retrofit

Volley is good general purpose async HTTP library, while Retrofit specifically concentrates on implementing a REST client.

Both of these libraries will handle much of the low-level detail that you're dealing with in your example.

Whether you continue to use your DefaultHttpClient code, or use Volley or Retrofit, you're definitely going to want to make sure that your network requests happen on a background thread so that you don't block the UI thread. It's not clear from your example whether you're doing that.

GreyBeardedGeek
  • 29,460
  • 2
  • 47
  • 67
0

you may also using Httpurlconnection please check link and you get more idea. or Httpsurlconnection

Arpan24x7
  • 648
  • 5
  • 24