在android中通过HTTP put请求将JSON发送到服务器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21376743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:27:25  来源:igfitidea点击:

send JSON to server via HTTP put request in android

androidjsonxively

提问by Jimit

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

如何将给定的 json 包装成字符串并通过 android 中的 Http put 请求将其发送到服务器?

This is how my json look like.

这就是我的 json 的样子。

    {
    "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.

上面是我的json数组。

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

请帮忙解决这个问题

回答by Shayan Pourvatan

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 datastreamListthat 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 , idand value), actually i think you have two class like bellow:

datastreamListfor 语句中使用的此示例中,您必须为要发送到服务器的所有值提供一个列表(一个具有 2 个属性的类的列表, id以及value),实际上我认为您有两个类,如下所示:

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 objectto json.

并且在您的代码中,您必须有一个要发送到服务器的 A 类对象,因此您可以使用第一部分将您objectjson.

回答by Vipul Purohit

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

如果您更喜欢使用库,那么我更喜欢您使用Kaush 的Ion Library

Form this library you can simply post your JSON like this :

形成这个库,您可以像这样简单地发布您的 JSON:

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

回答by jos

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

'{' 括号代表一个对象,'[' 代表一个数组或列表。在你的情况下创建一个bean

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

use org.codehaus.Hymanson:Hymanson-xcjar for json parssing

使用org.codehaus.Hymanson:Hymanson-xcjar 进行 json 解析

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

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

使用 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.

在服务器端将其作为字符串获取并解析它。

回答by Hyman Li

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

这是一个可以帮助您的 android 客户端库:Httpzoid - Android REST (JSON) 客户端,它有一些示例,您可以轻松地发布帖子,获取请求。 https://github.com/kodart/Httpzoid

回答by Pratik Butani

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

只是您必须作为字符串发送,以便将以下 JSON 数据存储在字符串中

{
    "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()));