send JSON to server via HTTP put request in androi

2020-06-19 02:40发布

问题:

How to wrap given json to string and send it to server via Http put request in android?

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

above is my json array.

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

please help on this

回答1:

this is one sample.

    JSONObject Parent = new JSONObject();
    JSONArray array = new JSONArray();

    for (int i = 0 ; i < datastreamList.size() ; i++)
    {
        JSONObject jsonObj = new JSONObject();

        jsonObj.put("id", datastreamList.get(i).GetId());
        jsonObj.put("current_value", datastreamList.get(i).GetCurrentValue());
        array.put(jsonObj);
    }       
    Parent.put("datastreams", array);       
    Parent.put("version", version);

and for sending that:

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);
    StringEntity se = new StringEntity( Parent.toString());  
    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    post.setHeader("Accept", "application/json");
    post.setHeader("Content-type", "application/json");
    post.setEntity(se);
    client.execute(post);

EDIT

in this sample datastreamList that used in for statement is a list that you must have for all value that want send to server ( one list of one class that have 2 property , id and value ), actually i think you have two class like bellow:

class A {

List<Datastreams> datastreamList
String version;
//get
//set
}

class Datastreams {

String id;
String current_value; // or int
//get
//set
}

and in your code you must have one object of A class that want send to server, so you can use first part to map your object to json.



回答2:

If you prefer to use a library then I'll prefer you to use Ion Library by Kaush.

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


回答3:

Just you have to send as a String so store following JSON data in String

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

then you have to send like:

pairs.add(new BasicNameValuePair("data", finalJsonObject.toString()));


回答4:

The '{' bracket represent a object and '[' represent an array or list. In your case create a bean

YourObj{
private String version;
private List<DataStream> datastreams;
//getters
//setters 
}
DataStream{
private String id;
private String current_value;
//getters
//setters
}

use org.codehaus.jackson:jackson-xc jar for json parssing

use ObjectMapper

String to Object

 YourObj obj = new ObjectMapper().readValue(stringyouwanttopass,new TypeReference<YourObj>(){});

now you can use the parsed value.

or you can set the values to the YourObj

YourObj obj =new YourObj();
obj.setVersion(1.0.0);
List<Datastream> datastreams=new ArrayList<Datastream>();
Datastream datestr=new Datastream();
datestr.setId("example");
datestr.setCurrent_value("333");
datastreams.add(datestr);
datestr.setId("key");
datestr.setCurrent_value("value");
datastreams.add(datestr);
datestr.setId("datastream");
datestr.setCurrent_value("1337");
datastreams.add(datestr);
JSONObject jsonget = new JSONObject(appObject);
jsonget.toString();

Connecting server using Jersey

Client client = Client.create();
WebResource webResource = client.resource("serverURl");
ClientResponse response = webResource.path("somePath")
                    .type("application/json").accept("application/json")
                    .post(ClientResponse.class, jsonget.toString());

in the server side get it as string and parse it.



回答5:

here is a android Client library can help you: Httpzoid - Android REST (JSON) Client,it has some examples and you can do put post,get request easily. https://github.com/kodart/Httpzoid