POST Android json数据

时间:2015-06-08 10:50:43

标签: java android json http

我正在尝试将一些数据发布到我的服务器,但我不知道为什么,我总是收到400条消息。

我想发送这个POST结构:

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

如果我发送curl或wget,我会获得200 Http状态。

我在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");
    }
}

我不知道这是否是完全相同的结构,这是我的结论,因为在chrome上使用Postman,而curl或wget,获得200状态。

有人可以帮助我吗?

如果你想尝试的URL是在顶部的POST方法。

1 个答案:

答案 0 :(得分:1)

在JSONObject中添加params,如下所示:

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

在代码中更改:

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