【问题标题】:How to POST data in Android to server in JSON format?如何以 JSON 格式将 Android 中的数据发布到服务器?
【发布时间】:2023-03-18 12:35:01
【问题描述】:

我有这个 JSON 字符串。我想将它发布到服务器(即使用 POST 方法)。如何在 Android 中做到这一点?

JSON 字符串:

{
    "clientId": "ID:1234-1234",
    "device": {
        "userAgent": "myUA",
        "capabilities": {
            "sms": true,
            "data": true,
            "gps": true,
            "keyValue": {
                "Key2": "MyValue2",
                "Key1": "myvalue1"
            }
        },
        "screen": {
            "width": 45,
            "height": 32
        },
        "keyValue": {
            "DevcKey2": "myValue2",
            "DevcKey1": "myValue1"
        }
    },
    "time": 1294617435368
}

如何形成这个 JSON 数组并将其 POST 到服务器?

【问题讨论】:

标签: java android json post


【解决方案1】:

我自己做的。

JSONObject returnedJObject= new JSONObject();
JSONObject KeyvalspairJObject=new JSONObject ();
JSONObject devcKeyvalspairJObject=new JSONObject ();
JSONObject capabilityJObject=new JSONObject();
JSONObject ScreenDimensionsJObject =new JSONObject();
JSONObject deviceJObject= new JSONObject();
try{
    KeyvalspairJObject.put("key1","val1");
    KeyvalspairJObject.put("key2","val2");
    capabilityJObject.put("sms", false);
    capabilityJObject.put("data", true);
    capabilityJObject.put("gps", true);
    capabilityJObject.put("wifi", true);
    capabilityJObject.put("keyValue", KeyvalspairJObject);
    ScreenDimensionsJObject.put("width", 45);
    ScreenDimensionsJObject.put("height", 45);
    devcKeyvalspairJObject.put("Devckey1","val1");
    devcKeyvalspairJObject.put("DEVCkey2","val2");
    deviceJObject.put("userAgent", "MYUserAgent");
    deviceJObject.put("capabilities", capabilityJObject);
    deviceJObject.put("screen", ScreenDimensionsJObject);
    deviceJObject.put("keyValue", devcKeyvalspairJObject);

    returnedJObject.put("clientId", "ID:1234-1234");
    returnedJObject.put("carrier","TMobile");
    returnedJObject.put("device",deviceJObject);
    returnedJObject.put("time",1294617435);
    returnedJObject.put("msisdn","1234567890");
    returnedJObject.put("timezone","GMT");
}
catch(JSONException e)
{
}

这就是我们向服务器发送 JSON 数据的方式。

public String putDataToServer(String url,JSONObject returnedJObject) throws Throwable
{
    HttpPost request = new HttpPost(url);
    JSONStringer json = new JSONStringer();
    StringBuilder sb=new StringBuilder();


    if (returnedJObject!=null) 
    {
        Iterator<String> itKeys = returnedJObject.keys();
        if(itKeys.hasNext())
            json.object();
        while (itKeys.hasNext()) 
        {
            String k=itKeys.next();
            json.key(k).value(returnedJObject.get(k));
            Log.e("keys "+k,"value "+returnedJObject.get(k).toString());
        }             
    }
    json.endObject();


    StringEntity entity = new StringEntity(json.toString());
                         entity.setContentType("application/json;charset=UTF-8");
    entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
    request.setHeader("Accept", "application/json");
    request.setEntity(entity); 

    HttpResponse response =null;
    DefaultHttpClient httpClient = new DefaultHttpClient();

    HttpConnectionParams.setSoTimeout(httpClient.getParams(), Constants.ANDROID_CONNECTION_TIMEOUT*1000); 
    HttpConnectionParams.setConnectionTimeout(httpClient.getParams(),Constants.ANDROID_CONNECTION_TIMEOUT*1000); 
    try{
        response = httpClient.execute(request); 
    }
    catch(SocketException se)
    {
        Log.e("SocketException", se+"");
        throw se;
    }
    InputStream in = response.getEntity().getContent();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    String line = null;
    while((line = reader.readLine()) != null){
        sb.append(line);
    }
    return sb.toString();
}

【讨论】:

  • 为什么putData中的jsonObj参数叫returnedJObject?它不代表需要发送的对象吗?同样对我来说,它不起作用我从服务器获得“无输入数据”,代码为 200
  • 只是为了使下面的代码与上面的代码同步,我使用了返回的JObject。使用其他名称不会破坏代码;)。但感谢您指出这一点。如果您收到代码 200,那么它必须是来自服务器的成功响应。 200 代表“状态正常”。
  • 是的,但我得到的响应意味着服务器没有任何输入,我会尝试与处理 API 的人交谈(问题一定存在)但他没有回答我今天的电子邮件
  • 你可能是服务器人员,可以让你对此有更多的了解。
【解决方案2】:

如果您已经将 JSON 作为字符串,只需使用常规 HTTP 连接 (URL.openConnection()) 将其发布。无需解析它或类似的东西。

【讨论】:

    【解决方案3】:

    看看这段代码

    https://gist.github.com/9457c486af9644cf6b18

    查看 retrieveJSONArray(ArrayList jsonArray,String[] key)retrieveJSONString(ArrayList jsonObject)

    【讨论】:

    • 你想创建JSON字符串.......基本逻辑在retrieveJSONString中,但它是根据我的逻辑和要求定制的......
    【解决方案4】:
    JSONObject returnedJObject= new JSONObject();
    
    url = "http://49.50.76.75/website/exxx/api.php";
    
    // makeSignupRequest();
    
    try {
        returnedJObject.put("email",eemail);
        returnedJObject.put("password",passwrd);
        returnedJObject.put("type","customer");
        returnedJObject.put("method","register");
        returnedJObject.put("username",usr);
    
        try {
            putDataToServer(url, returnedJObject);
    
        }
        catch (Throwable m) {
            m.printStackTrace();
        }
    }
    

    【讨论】:

    • 并使用 putdatatoserver() 方法。但在服务器端不起作用
    【解决方案5】:

    如果这不是一个“爱好”应用程序,只需进行一两个服务调用,我会考虑查看异步 HTTP 或 REST 库。

    有几个值得考虑的,包括来自 Google 的 Volley:https://developer.android.com/training/volley/index.html

    以及从 Square 进行改造:http://square.github.io/retrofit

    Volley 是一个很好的通用异步 HTTP 库,而 Retrofit 专门专注于实现 REST 客户端。

    这两个库都将处理您在示例中处理的大部分低级细节。

    无论您是继续使用 DefaultHttpClient 代码,还是使用 Volley 或 Retrofit,您肯定会希望确保您的网络请求发生在后台线程上,以免阻塞 UI 线程。从您的示例中不清楚您是否正在这样做。

    【讨论】:

      【解决方案6】:

      你也可以使用Httpurlconnection 请检查链接,你会得到更多的想法。或Httpsurlconnection

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-04-14
        • 1970-01-01
        • 2013-01-06
        • 1970-01-01
        • 2018-12-25
        • 2014-01-03
        • 1970-01-01
        相关资源
        最近更新 更多