由网友(-爱我你怕了吗,)分享简介:如何包装给JSON字符串,并通过HTTP发送到服务器把请求的Android?How to wrap given json to string and send it to server via Http put request in android?这是我的JSON的样子。 This is how my js...
如何包装给JSON字符串,并通过HTTP发送到服务器把请求的Android?
How to wrap given json to string and send it to server via Http put request in android?
这是我的JSON的样子。
This is how my json look like.
{
"version": "1.0.0",
"datastreams": [
{
"id": "example",
"current_value": "333"
},
{
"id": "key",
"current_value": "value"
},
{
"id": "datastream",
"current_value": "1337"
}
]
}
以上是我的JSON数组。
above is my json array.
我是怎么写的code,但它不工作
below is how I wrote the code but, its not working
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;
}
请在这方面的帮助。
推荐答案
如果您preFER使用一个库,然后我会preFER您使用的离子库被Kaush 的。
If you prefer to use a library then I'll prefer you to use Ion Library by Kaush.
构成本库,你可以简单地张贴您的JSON是这样的:
Form this library you can simply post your JSON like this :
JsonObject json = new JsonObject();
json.addProperty("foo", "bar");
Ion.with(context, "http://example.com/post")
.setJsonObjectBody(json)
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
@Override
public void onCompleted(Exception e, JsonObject result) {
// do stuff with the result or error
}
});
相关推荐
最新文章