如何将给定的json包装到字符串并通过Http put请求将其发送到服务器?
这就是我的json的样子.
{ "version": "1.0.0", "datastreams": [ { "id": "example", "current_value": "333" }, { "id": "key", "current_value": "value" }, { "id": "datastream", "current_value": "1337" } ] }
上面是我的json数组.
下面是我编写代码的方法,但它不起作用
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; }
请帮忙