在 Android 中使用 Volley 库将数据(POST 或 GET)发送到服务器

Send data (POST or GET) to server with Volley Lib in Android

我开发了一个应用程序,我将通过 Json 从 phone 向服务器发送数据,为此我使用 Volley Android.
中的库 但是我无法向服务器发送数据!

我的简单 php 代码:

$name = $_GET["name"];
$j = array('name' =>$name);
echo json_encode($j);

我的java代码:

    private void makeJsonObjectRequest() {
        mRequestQueue = Volley.newRequestQueue(this);
        String url = "http://my-site-name/sampleGET.php";

        StringRequest jsonObjReq = new StringRequest(
            Request.Method.GET, 
            url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.d("result:", response);
                    Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
                }
            }, 
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d("err", "Error: " + error.getMessage());
                    makeJsonObjectRequest();
                }
            }
        ){
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();
                params.put("name", "json");
                return params;
            }
        };
        mRequestQueue.add(jsonObjReq);
    }

它还得到了下面 link 的帮助:Click to see link

但仍然无法使用它并从手机向服务器发送数据(POST 或 GET)!!!
我该怎么做?

根据

的建议

从当前代码中删除此方法:

        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();
            params.put("name", "json");
            return params;
        }

并改写 getBody() 方法。然后,根据以下示例将其调整为 return 您需要的 json 数据作为请求正文:

    public byte[] getBody() throws AuthFailureError {
        JSONObject js = new JSONObject();
        try {
               js.put("fieldName", "fieldValue");
        } catch (JSONException e) {
               e.printStackTrace();
        }

        return js.toString().getBytes();
    }

然后在 php 中解码您的 json 数据:

    $jsonRequest = json_decode(stream_get_contents(STDIN));
    var_dump($jsonRequest);

如果需要更多信息,请告诉我。