使用Volley Library从服务器发送和获取数据(Android - PHP)

时间:2018-03-16 08:00:37

标签: php android json android-volley jsonobjectrequest

我需要将JSONObject发送到服务器并从中获取其他JSONObject。但是我无法将JSONObject发送到服务器,换句话说,我的JSONObject被发送到具有空值的服务器。

Android代码:

{
  "dependencies": {
    "Microsoft.AspNetCore.Diagnostics": "1.1.0",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.1.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.1.0",
    "Microsoft.Extensions.Logging.Console": "1.1.0",
    "Microsoft.AspNetCore.StaticFiles": "1.1.0",
    "EntityFramework": "6.1.3",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.1.0",
    "Microsoft.Extensions.Configuration.Json": "1.1.0"
  },

  "tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
  },

  "frameworks": {
    "net461": {
      "dependencies": {
        "Data": {
          "target": "project"
        }

      },
      "frameworkAssemblies": {
        "System.Configuration": "4.0.0.0"
      }
    }
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "appsettings.json",
      "appsettings.Staging.json",
      "appsettings.Production.json",
      "web.config"
    ]
  },

  "scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

PHP代码:

JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST,
                getUrl(), new JSONObject("{\"command\":\"get_ad_list\"}"), new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.e("xxxxxxxxx-result ", response.toString());
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("xxxxxxxxx-error ", error.toString());
            }
        });
        request.setRetryPolicy(new DefaultRetryPolicy(8000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        requestQueue.add(request);

2 个答案:

答案 0 :(得分:0)

protected void fetchWebpage() {
    /*
        Json
     */
    final JSONObject json = new JSONObject();
    final JSONObject manJson = new JSONObject();
    try {
        manJson.put("VALUE_1", "HELLO");
        manJson.put("VALUE_2", "AM");
        manJson.put("VALUE_3", "VOLLEY");
        /*
            More values here
        */
        final String j = json.put("UPDATE", manJson).toString();
        // starts here
        final String base_url = "https://google.com";
        // Instantiate the RequestQueue.
        RequestQueue queue = Volley.newRequestQueue(this);
        // Request a string response from the provided URL.
        StringRequest stringRequest = new StringRequest(Request.Method.POST, base_url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                /*

                    YOUR RESPONSE FROM SERVER IS HERE
                 */
                Log.i(TAG, "received "+response);
                // process your response if return json
                try {
                    JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
                    Sting value_returned_from_server_1 = object.getString("value_you_return_1");
                    Sting value_returned_from_server_2 = object.getString("value_you_return_2");
                    /*
                        MORE VALUES HERE
                     */
                } catch (JSONException e) {
                    /*Show results*/
                    Log.i(TAG, "ERROR JSON "+e.getMessage());
                    return;
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //perform operation here after getting error
                /* unsuccessfully result - no internet */
                return;
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                //pack message into json
                try {
                    params.put("json", j.toString());
                } catch (Exception e) {
                    //Log.i(TAG,"Map error: Unable to compile post");
                }
                return params;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                params.put("Content-Type", "application/x-www-form-urlencoded");
                return params;
            }
        };
        // Add the request to the RequestQueue.
        queue.add(stringRequest);
        // ends here
        return;
    } catch (Exception e) {
        //Log.i(TAG,"ERROR: Unable to get setup settings");
    } // end exception write
    return;
}

答案 1 :(得分:0)

试试这个:

   JSONObject jsonObject = new JSONObject();
    try {
        jsonObject.put("command","get_ad_list");
    } catch (JSONException e) {
        e.printStackTrace();
    }



     JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST,
            getUrl(), jsonObject, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Log.e("xxxxxxxxx-result ", response.toString());
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("xxxxxxxxx-error ", error.toString());
        }
    });
    request.setRetryPolicy(new DefaultRetryPolicy(8000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    RequestQueue requestQueue = Volley.newRequestQueue(context);
    requestQueue.add(request);