我如何通过 android 中的 POST 将复杂的 JSON 对象 post 发送到服务器?

How can i post a complex JSON object to a server via POST in android?

我有复杂的 JSON 对象,我想通过 HTTP POST 请求将其 post 发送到服务器。 我看过很多 Volley 库的例子,但它们都只适用于简单的键值对 (HashMap)。 谁能建议一个处理复杂 JSON 对象的 posting 的库?

我不知道任何与 JSONObjcet 一起工作的库的引用,但我在这里有一个与 AsyncTask 一起工作的代码,它正在将 JSONObjects 发送到服务器:

    private class BackgroundOperation extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) 
            //Your network connection code should be here .
            String response = postCall("Put your WebService url here");
            return response ;
        }

        @Override
        protected void onPostExecute(String result) {
            //Print your response here .
            Log.d("Post Response",result);

        }

        @Override
        protected void onPreExecute() {}

        @Override
        protected void onProgressUpdate(Void... values) {}
    }

        public static String postCall(JSONObject josnobj) {
        String result ="";
        try {
            //Connect
            HttpURLConnection urlConnection = (HttpURLConnection) ((new URL(uri).openConnection()));
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setRequestProperty("Accept", "application/json");
            urlConnection.setRequestMethod("POST");
            urlConnection.connect();
            //Write
            OutputStream outputStream = urlConnection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
//Call parserUsuarioJson() inside write(),Make sure it is returning proper json string .
            writer.write(josnobj.toString());
            writer.close();
            outputStream.close();

            //Read
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
            bufferedReader.close();
            result = sb.toString();
        } catch (UnsupportedEncodingException e){
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

现在您可以使用以下代码从 activity 的 onCreate() 函数中调用上面的代码。

   JSONObject jobj = new JSONObject();
jobj.put("name","yourname");
jobj.put("email","mail");
jobj.put("pass","pass");
    new BackgroundOperation().execute(jobj.toString());

注意:不要忘记在您的 manifest.xml

中提及以下许可
<uses-permission android:name="android.permission.INTERNET" />