POST Android json data

187 Views Asked by At

I'm trying to POST some data to my server, but I don't know why, I always get 400 messages from it.

I want to send this POST structure:

POST /api/v0.1/observations/3 HTTP/1.1
Host: 54.154.117.132`
Content-Type: application/json
Cache-Control: no-cache

{ 
   "data" : 
   { 
      "field1" : 1111111 
   }, 
   "timestamp": "2015-05-13T12:23:42.648738" 
}

If I send that with curl, or wget, I get a 200 Http status.

I'm doing this on android:

public void POST(String json) throws MalformedURLException {

    int httpResult;
    //URL url = new URL(getString(R.string.URL));
    URL url = new URL(getString(R.string.URL_test2));
    HttpURLConnection con;

    JSONObject obj1 = new JSONObject();
    JSONObject obj2 = new JSONObject();

    try {
        obj1.put("field1",222);
        obj2.put("data", obj1);
        obj2.put("timestamp", "2015-06-8T12:05:42.648738");
    } catch (JSONException e) {
        e.printStackTrace();
    }


    try {
        con = (HttpURLConnection) url.openConnection();
        con.setDoOutput(true);
        con.setRequestMethod("POST");
        con.setUseCaches(false);
        con.setConnectTimeout(10000);
        con.setReadTimeout(10000);
        con.setRequestProperty("Content-Type","application/json");
        con.setRequestProperty("Host", "54.154.117.132");
        con.connect();

        OutputStreamWriter out = new   OutputStreamWriter(con.getOutputStream());
        out.write(obj2.toString());
        out.close();

        httpResult = con.getResponseCode();
        Log.i("Request","--> "+httpResult);
        if (httpResult == HttpURLConnection.HTTP_OK) Log.i("HTTP"," --> all ok");
        else Log.i("HTTP", " --> smthg wrong!");

    } catch (IOException e) {
        Log.i("ERROR"," !!! Interrupcion a la hora de conectarse");
    }
}

I don't know if this is exactly the same structure, that's is my conclusion, because using Postman on chrome, and curl or wget, get 200 status.

Someone can help me?

The URL if you want to try is on POST method on the top.

1

There are 1 best solutions below

6
On BEST ANSWER

Add your params in JSONObject like below:

JSONObject jsonObject = new JSONObject();
 jsonObject .put("field", 222);
        JSONObject mainObject = new JSONObject();
        try {
            mainObject .put("data",jsonObject);
            mainObject .put("timestamp","2015-05-13T12:23:42.648738");
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

And change here in code:

OutputStreamWriter out = new   OutputStreamWriter(con.getOutputStream());
        out.write(mainObject.toString());  //change to mainObject from obj2
        out.close();