JSON per HTTP an den Server senden Anfrage in Android stellen

Wie man einen gegebenen Json in einen String packt und ihn per HTTP-Put-Request in Android an den Server sendet?

So sieht mein Json aus.

    {
    "version": "1.0.0",
    "datastreams": [
        {
            "id": "example",
            "current_value": "333"
        },
        {
            "id": "key",
            "current_value": "value"
        },
        {
            "id": "datastream",
            "current_value": "1337"
        }
    ]
}

oben ist mein JSON-Array.

Unten ist, wie ich den Code geschrieben habe, aber es funktioniert nicht

        protected String doInBackground(Void... params) {
            String text = null;
            try {
                JSONObject child1 = new JSONObject();
                try{
                    child1.put("id", "LED");
                    child1.put("current_value", "0");


                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


                JSONArray jsonArray = new JSONArray();

                jsonArray.put(child1);

                JSONObject datastreams = new JSONObject();
                datastreams.put("datastreams", jsonArray);  

                JSONObject version = new JSONObject();
                version.put("version", "1.0.0");
                version.put("version", datastreams);


             HttpClient httpClient = new DefaultHttpClient();
             HttpContext localContext = new BasicHttpContext();
             HttpPut put = new HttpPut("url");
             put.addHeader("X-Apikey","");
             StringEntity se = new StringEntity( version.toString());  
             se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

             put.addHeader("Accept", "application/json");
             put.addHeader("Content-type", "application/json");
             put.setEntity(se);


             try{

                   HttpResponse response = httpClient.execute(put, localContext);
                   HttpEntity entity = response.getEntity();
                   text = getASCIIContentFromEntity(entity);
             }
              catch (Exception e) {
                 return e.getLocalizedMessage();
             }


        }catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
            return text;
        }

Bitte helfen Sie dabei

Antworten auf die Frage(5)

Ihre Antwort auf die Frage