在PHP中使用截击和接收发送post请求

时间:2022-10-22 22:48:36

I am trying to use volley in my project to handle all my HTTP request since it's the most efficient one as far as I know. So I started to learn volley by following this AndroidHive tutorial.

我正在尝试在我的项目中使用截击来处理所有HTTP请求,因为它是我所知道的最有效的请求。所以我开始学习排球,跟随这个android蜂巢教程。

My first GET request was successful. Then I moved on to POST request and I failed. I saw on Stack Overflow many people had problems combining post request of volley with PHP. I believe we cannot access it using the normal way that is $_POST[""] as volley sends a JSON object to the URL which we specify.

我的第一个请求是成功的。然后我继续发布请求,但失败了。我在Stack Overflow上看到很多人都有问题,他们结合了post请求和PHP。我认为我们不能使用$_POST["]的常规方式访问它,因为volley将JSON对象发送到我们指定的URL。

There were lots of solutions which I tried but didn't succeed. I guess there should be a simple and standard way of using volley with PHP. So I would like to know what do I need to do in order to receive the json object sent by volley in my PHP code.

我尝试了很多方法,但没有成功。我想应该有一种简单而标准的方法来使用PHP。因此,我想知道,为了在PHP代码中接收volley发送的json对象,我需要做什么。

And also how do I check if volley is really sending a JSON object?

如何检查volley是否真的发送JSON对象?

My volley code to send simple post request:

我的截击码发送简单的邮件请求:

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);

My PHP code to receive json object: (I am pretty sure this is the wrong way, I am not that good in PHP)

我的PHP代码接收json对象:

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

I tried lots of ways of accepting JSON object in PHP like this one as well echo file_get_contents('php://input');

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

The Result

结果

null

EDIT (The correct way thanks to Georgian Benetatos)

编辑(感谢格鲁吉亚Benetatos的正确方式)

I created the class as you mentioned the class name is CustomRequest which is as follows:

我创建了类,正如你提到的类名是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));
            }
    }

}

Now in my activity I called the following:

在我的活动中,我称之为:

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);

My PHP code is as follow:

我的PHP代码如下:

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

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

Now its returning the correct value:

现在它返回正确的值:

Droider

5 个解决方案

#1


16  

Had a lot of problems myself, try this !

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

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);
}

PHP

PHP

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

echo json_encode($response);

You have to make a map, the map supports key-value type, and than you post with volley. In php you get $variable = $_POST["key_from_map"] to retreive it's value in the $variable Then you build up the response and json_encode it.

你必须做一个映射,映射支持键值类型,而不是你用截击。在php中,你会得到$variable = $_POST["key_from_map"]来retreive它在$变量中的值,然后你构建响应并对其进行json_encode。

Here is a php example of how to query sql and post answer back as JSON

下面是一个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);

You can see here that the response type is JSONObject

可以看到,响应类型是JSONObject。

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

Look at the listener's parameter!

看一下监听器的参数!

#2


6  

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);

and in your server side:

在服务器端:

<?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);    
?>

open MyName.txt and see the result.

开放的名字。txt并查看结果。

#3


4  

Here is a simple code to send post request to php script

下面是发送post请求到php脚本的简单代码。

MainActivity.java

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private static final String REGISTER_URL = "http://simplifiedcoding.16mb.com/UserRegistration/volleyRegister.php";

public static final String KEY_USERNAME = "username";
public static final String KEY_PASSWORD = "password";
public static final String KEY_EMAIL = "email";


private EditText editTextUsername;
private EditText editTextEmail;
private EditText editTextPassword;

private Button buttonRegister;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    editTextUsername = (EditText) findViewById(R.id.editTextUsername);
    editTextPassword = (EditText) findViewById(R.id.editTextPassword);
    editTextEmail= (EditText) findViewById(R.id.editTextEmail);

    buttonRegister = (Button) findViewById(R.id.buttonRegister);

    buttonRegister.setOnClickListener(this);
}

private void registerUser(){
    final String username = editTextUsername.getText().toString().trim();
    final String password = editTextPassword.getText().toString().trim();
    final String email = editTextEmail.getText().toString().trim();

    StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Toast.makeText(MainActivity.this,response,Toast.LENGTH_LONG).show();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
                }
            }){
        @Override
        protected Map<String,String> getParams(){
            Map<String,String> params = new HashMap<String, String>();
            params.put(KEY_USERNAME,username);
            params.put(KEY_PASSWORD,password);
            params.put(KEY_EMAIL, email);
            return params;
        }

    };

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}

@Override
public void onClick(View v) {
    if(v == buttonRegister){
        registerUser();
    }
}
}

volleyRegister.php

volleyRegister.php

<?php

if($_SERVER['REQUEST_METHOD']=='POST'){
    $username = $_POST['username'];
    $email = $_POST['email'];
    $password = $_POST['password'];

    require_once('dbConnect.php');

    $sql = "INSERT INTO volley (username,password,email) VALUES ('$username','$email','$password')";


    if(mysqli_query($con,$sql)){
        echo "Successfully Registered";
    }else{
        echo "Could not register";

    }
}else{
echo 'error'}
}

Source: Android Volley Post Request Tutorial

源:Android Volley Post请求教程

#4


3  

always use StringRequest with volley as it is safer way to get the response from server , if JSON is damaged or not properly formatted.

如果JSON被损坏或格式不正确,那么总是使用volley的StringRequest作为获取服务器响应的更安全的方法。

ANDROID CODE :

ANDROID代码:

StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {JSONObject jsonObject = new JSONObject(response);
            } catch (JSONException ignored) {
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            if (volleyError instanceof TimeoutError) {
            }
        }
    }) {
        @Override
        public Map<String, String> getParams() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<>();
            headers.put("name", "Droider");
            return headers;
        }

        @Override
        public Priority getPriority() {
            return Priority.IMMEDIATE;
        }
    };
    ApplicationController.getInstance().addToRequestQueue(stringRequest);

PHP CODE :

PHP代码:

<?php
   $name = $_POST["name"];
   $j = array('name' =>$name);
   echo json_encode($j);
?>

#5


0  

This works fine for me if this helps anyone

如果这对任何人都有帮助的话,这对我来说是可行的

public class LoginActivity extends AppCompatActivity {

    private EditText Email;
    private EditText Password;
    private String URL = "http://REPLACE ME WITH YOUR URL/login.php";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        TextView register = (TextView) findViewById(R.id.Register);
        TextView forgotten = (TextView) findViewById(R.id.Forgotten);
        Button login = (Button) findViewById(R.id.Login);
        Email = (EditText) findViewById(R.id.Email);
        Password = (EditText) findViewById(R.id.Password);
        Password.setImeOptions(EditorInfo.IME_ACTION_DONE);

        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RequestQueue MyRequestQueue = Volley.newRequestQueue  (LoginActivity.this);
                MyRequestQueue.add(MyStringRequest);
            }
        });
    }

StringRequest MyStringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Toast.makeText(getApplicationContext(),response.trim(), Toast.LENGTH_SHORT).show();
        }

    }, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getApplicationContext(),error.toString().trim(), Toast.LENGTH_LONG).show();
        }
    }) {
        protected Map<String, String> getParams() {
            final String email = Email.getText().toString().trim();
            final String password = Password.getText().toString().trim();

            Map<String, String> MyData = new HashMap<String, String>();
            MyData.put("email", email);
            MyData.put("password", password);
            return MyData;
        }
     };
 }

the login.php

<?php
    $message = $_POST["email"];
    echo $message;
?>

#1


16  

Had a lot of problems myself, try this !

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

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);
}

PHP

PHP

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

echo json_encode($response);

You have to make a map, the map supports key-value type, and than you post with volley. In php you get $variable = $_POST["key_from_map"] to retreive it's value in the $variable Then you build up the response and json_encode it.

你必须做一个映射,映射支持键值类型,而不是你用截击。在php中,你会得到$variable = $_POST["key_from_map"]来retreive它在$变量中的值,然后你构建响应并对其进行json_encode。

Here is a php example of how to query sql and post answer back as JSON

下面是一个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);

You can see here that the response type is JSONObject

可以看到,响应类型是JSONObject。

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

Look at the listener's parameter!

看一下监听器的参数!

#2


6  

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);

and in your server side:

在服务器端:

<?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);    
?>

open MyName.txt and see the result.

开放的名字。txt并查看结果。

#3


4  

Here is a simple code to send post request to php script

下面是发送post请求到php脚本的简单代码。

MainActivity.java

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private static final String REGISTER_URL = "http://simplifiedcoding.16mb.com/UserRegistration/volleyRegister.php";

public static final String KEY_USERNAME = "username";
public static final String KEY_PASSWORD = "password";
public static final String KEY_EMAIL = "email";


private EditText editTextUsername;
private EditText editTextEmail;
private EditText editTextPassword;

private Button buttonRegister;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    editTextUsername = (EditText) findViewById(R.id.editTextUsername);
    editTextPassword = (EditText) findViewById(R.id.editTextPassword);
    editTextEmail= (EditText) findViewById(R.id.editTextEmail);

    buttonRegister = (Button) findViewById(R.id.buttonRegister);

    buttonRegister.setOnClickListener(this);
}

private void registerUser(){
    final String username = editTextUsername.getText().toString().trim();
    final String password = editTextPassword.getText().toString().trim();
    final String email = editTextEmail.getText().toString().trim();

    StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Toast.makeText(MainActivity.this,response,Toast.LENGTH_LONG).show();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
                }
            }){
        @Override
        protected Map<String,String> getParams(){
            Map<String,String> params = new HashMap<String, String>();
            params.put(KEY_USERNAME,username);
            params.put(KEY_PASSWORD,password);
            params.put(KEY_EMAIL, email);
            return params;
        }

    };

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}

@Override
public void onClick(View v) {
    if(v == buttonRegister){
        registerUser();
    }
}
}

volleyRegister.php

volleyRegister.php

<?php

if($_SERVER['REQUEST_METHOD']=='POST'){
    $username = $_POST['username'];
    $email = $_POST['email'];
    $password = $_POST['password'];

    require_once('dbConnect.php');

    $sql = "INSERT INTO volley (username,password,email) VALUES ('$username','$email','$password')";


    if(mysqli_query($con,$sql)){
        echo "Successfully Registered";
    }else{
        echo "Could not register";

    }
}else{
echo 'error'}
}

Source: Android Volley Post Request Tutorial

源:Android Volley Post请求教程

#4


3  

always use StringRequest with volley as it is safer way to get the response from server , if JSON is damaged or not properly formatted.

如果JSON被损坏或格式不正确,那么总是使用volley的StringRequest作为获取服务器响应的更安全的方法。

ANDROID CODE :

ANDROID代码:

StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {JSONObject jsonObject = new JSONObject(response);
            } catch (JSONException ignored) {
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            if (volleyError instanceof TimeoutError) {
            }
        }
    }) {
        @Override
        public Map<String, String> getParams() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<>();
            headers.put("name", "Droider");
            return headers;
        }

        @Override
        public Priority getPriority() {
            return Priority.IMMEDIATE;
        }
    };
    ApplicationController.getInstance().addToRequestQueue(stringRequest);

PHP CODE :

PHP代码:

<?php
   $name = $_POST["name"];
   $j = array('name' =>$name);
   echo json_encode($j);
?>

#5


0  

This works fine for me if this helps anyone

如果这对任何人都有帮助的话,这对我来说是可行的

public class LoginActivity extends AppCompatActivity {

    private EditText Email;
    private EditText Password;
    private String URL = "http://REPLACE ME WITH YOUR URL/login.php";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        TextView register = (TextView) findViewById(R.id.Register);
        TextView forgotten = (TextView) findViewById(R.id.Forgotten);
        Button login = (Button) findViewById(R.id.Login);
        Email = (EditText) findViewById(R.id.Email);
        Password = (EditText) findViewById(R.id.Password);
        Password.setImeOptions(EditorInfo.IME_ACTION_DONE);

        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RequestQueue MyRequestQueue = Volley.newRequestQueue  (LoginActivity.this);
                MyRequestQueue.add(MyStringRequest);
            }
        });
    }

StringRequest MyStringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Toast.makeText(getApplicationContext(),response.trim(), Toast.LENGTH_SHORT).show();
        }

    }, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getApplicationContext(),error.toString().trim(), Toast.LENGTH_LONG).show();
        }
    }) {
        protected Map<String, String> getParams() {
            final String email = Email.getText().toString().trim();
            final String password = Password.getText().toString().trim();

            Map<String, String> MyData = new HashMap<String, String>();
            MyData.put("email", email);
            MyData.put("password", password);
            return MyData;
        }
     };
 }

the login.php

<?php
    $message = $_POST["email"];
    echo $message;
?>