使用凌空发送帖子请求并以 PHP 接收

2022-08-30 16:10:31

我正在尝试在我的项目中使用凌空抽射来处理我所有的HTTP请求,因为据我所知,这是最有效的一个。因此,我开始按照这个AndroidHive教程学习排球。

我的第一个 GET 请求成功了。然后我转到POST请求,我失败了。我在Stack Overflow上看到许多人在将发布凌空抽排请求与PHP相结合时遇到了问题。我相信我们不能使用正常的方式访问它,因为凌空将JSON对象发送到我们指定的URL。$_POST[""]

我尝试了很多解决方案,但没有成功。我想应该有一种简单而标准的方式在PHP中使用凌空抽射。因此,我想知道我需要做什么才能在我的PHP代码中接收通过凌空发送的json对象。

还有,我如何检查凌空飞行是否真的在发送JSON对象?

我的凌空代码发送简单的发布请求:

JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
                url, null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d(TAG, response.toString());
                        pDialog.hide();
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
                        pDialog.hide();
                    }
                }) {

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

        };

// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

我的PHP代码接收json对象:(我很确定这是错误的方式,我在PHP中不是那么好)

<?php
    $jsonReceiveData = json_encode($_POST);
    echo $jsonReceivedData;
?>

我尝试了很多在PHP中接受JSON对象的方法,比如这个echo file_get_contents('php://input');

成果

null

编辑(正确的方式感谢格鲁吉亚贝内塔托斯)

我创建了你提到的类,类名如下:CustomRequest

import java.io.UnsupportedEncodingException;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;

public class CustomRequest extends Request<JSONObject>{

      private Listener<JSONObject> listener;
      private Map<String, String> params;

      public CustomRequest(String url, Map<String, String> params,
                Listener<JSONObject> reponseListener, ErrorListener errorListener) {
            super(Method.GET, url, errorListener);
            this.listener = reponseListener;
            this.params = params;
      }

      public CustomRequest(int method, String url, Map<String, String> params,
                Listener<JSONObject> reponseListener, ErrorListener errorListener) {
            super(method, url, errorListener);
            this.listener = reponseListener;
            this.params = params;
        }

    @Override
    protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
      return params;
    };

    @Override
    protected void deliverResponse(JSONObject response) {
        listener.onResponse(response);
    }

    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
         try {
                String jsonString = new String(response.data,
                        HttpHeaderParser.parseCharset(response.headers));
                return Response.success(new JSONObject(jsonString),
                        HttpHeaderParser.parseCacheHeaders(response));
            } catch (UnsupportedEncodingException e) {
                return Response.error(new ParseError(e));
            } catch (JSONException je) {
                return Response.error(new ParseError(je));
            }
    }

}

现在在我的活动中,我调用了以下内容:

String url = some valid url;
Map<String, String> params = new HashMap<String, String>();
params.put("name", "Droider");

CustomRequest jsObjRequest = new CustomRequest(Method.POST, url, params, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    Log.d("Response: ", response.toString());
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError response) {
                Log.d("Response: ", response.toString());
            }
        });
        AppController.getInstance().addToRequestQueue(jsObjRequest);

我的PHP代码如下:

<?php
$name = $_POST["name"];

$j = array('name' =>$name);
echo json_encode($j);
?>

现在它返回正确的值:

Droider

答案 1

自己有很多问题,试试这个!

public class CustomRequest extends Request<JSONObject> {

private Listener<JSONObject> listener;
private Map<String, String> params;

public CustomRequest(String url,Map<String, String> params, Listener<JSONObject> responseListener, ErrorListener errorListener) {
    super(Method.GET, url, errorListener);
    this.listener = responseListener;
    this.params = params;
}

public CustomRequest(int method, String url,Map<String, String> params, Listener<JSONObject> reponseListener, ErrorListener errorListener) {
    super(method, url, errorListener);
    this.listener = reponseListener;
    this.params = params;
}

@Override
protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
    return params;
};

@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
    try {
        String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));

        return Response.success(new JSONObject(jsonString), HttpHeaderParser.parseCacheHeaders(response));
    } catch (UnsupportedEncodingException e) {
        return Response.error(new ParseError(e));
    } catch (JSONException je) {
        return Response.error(new ParseError(je));
    }
}

@Override
protected void deliverResponse(JSONObject response) {
    listener.onResponse(response);
}

菲律宾比索

$username = $_POST["username"];
$password = $_POST["password"];

echo json_encode($response);

你必须制作一个地图,地图支持键值类型,而不是你用凌空发布。在php中,你得到$variable = $_POST[“key_from_map”]来检索它在$variable中的价值,然后你建立响应并json_encode它。

下面是一个 php 示例,说明如何查询 sql 并将答案发布回 JSON

$response["devices"] = array();

    while ($row = mysqli_fetch_array($result)) {


        $device["id"] = $row["id"];
        $device["type"] = $row["type"];


        array_push($response["devices"], $device);  
    }

    $response["success"] = true;
    echo json_encode($response);

您可以在此处看到响应类型为 JSONObject

public CustomRequest(int method, String url,Map<String, String> params, Listener<JSONObject> reponseListener, ErrorListener errorListener)

查看侦听器的参数!


答案 2
JSONObject params = new JSONObject();
        try {
            params.put("name", "Droider");
        } catch (JSONException e) {
            e.printStackTrace();
        }
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
                url, params,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d(TAG, response.toString());
                        pDialog.hide();
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
                        pDialog.hide();
                    }
                }) {

                 @Override
                 public Map<String, String> getHeaders() throws AuthFailureError {
                        HashMap<String, String> headers = new HashMap<String, String>();
                        headers.put("Content-Type", "application/json; charset=utf-8");
                        return headers;  
                 } 

        };

// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

和在服务器端:

<?php
     $value = json_decode(file_get_contents('php://input'));
     $file = 'MyName.txt';
     file_put_contents($file, "The received name is {$value->name} ", FILE_APPEND | LOCK_EX);    
?>

打开并查看结果。MyName.txt


推荐