发送POST请求使用截击和接收PHP [英] Send post request using Volley and receive in PHP
问题描述
我想使用凌空在我的项目来处理我所有的HTTP请求,因为它是最高效的,据我所知。于是,我开始按照这个 AndroidHive教程了解抽射。
我的第一个GET请求成功。然后我转移到POST请求,我失败了。我看到堆栈溢出很多人不得不结合抽射POST请求与PHP的问题。我相信,使用正常的方式,是 $ _ POST []
作为凌空发送一个JSON对象,其中我们指定的网址。
有很多,我试过,但没有成功的解决方案。我想应该有使用凌空用PHP的简单和标准的方式。所以我想知道什么,我需要做的,以接收抽射我的PHP code发送的JSON对象。
和还我如何检查是否凌空真的发送一个JSON对象?
我的抽射code发送简单的post请求:
JsonObjectRequest jsonObjReq =新JsonObjectRequest(Method.POST,
URL,空,
新Response.Listener<的JSONObject>(){
@覆盖
公共无效onResponse(JSONObject的响应){
Log.d(TAG,response.toString());
pDialog.hide();
}
},新Response.ErrorListener(){
@覆盖
公共无效onErrorResponse(VolleyError错误){
VolleyLog.d(TAG,错误:+ error.getMessage());
pDialog.hide();
}
}){
@覆盖
保护地图<字符串,字符串> getParams()方法{
地图<字符串,字符串> PARAMS =新的HashMap<字符串,字符串>();
params.put(姓名,Droider);
返回PARAMS;
}
};
//添加请求,请求队列
。AppController.getInstance()addToRequestQueue(jsonObjReq,tag_json_obj);
我的PHP code接收JSON对象:(我是pretty的肯定,这是错误的方式,我不是在PHP好)
< PHP
$ jsonReceiveData = json_en code($ _ POST);
回声$ jsonReceivedData;
?>
我试过很多接受JSON对象的方式在PHP中像这样的还有
回声的file_get_contents(PHP://输入');
结果
空
修改(正确的做法应该感谢格鲁吉亚Benetatos)
我创建的类正如你所提到的类名为 CustomRequest
这是如下:
进口java.io.UnsupportedEncodingException;
进口的java.util.Map;
进口org.json.JSONException;
进口org.json.JSONObject;
进口com.android.volley.NetworkResponse;
进口com.android.volley.ParseError;
进口com.android.volley.Request;
进口com.android.volley.Response;
进口com.android.volley.Response.ErrorListener;
进口com.android.volley.Response.Listener;
进口com.android.volley.toolbox.HttpHeaderParser;
公共类CustomRequest扩展请求<的JSONObject> {
私人听者LT;的JSONObject>侦听器;
私人地图<字符串,字符串> PARAMS;
公共CustomRequest(字符串URL,地图<字符串,字符串>参数,可以
收听LT;的JSONObject> reponseListener,ErrorListener errorListener){
超(Method.GET,网址,errorListener);
this.listener = reponseListener;
this.params = PARAMS;
}
公共CustomRequest(INT方法,字符串URL,地图<字符串,字符串>参数,可以
收听LT;的JSONObject> reponseListener,ErrorListener errorListener){
超(方法,URL,errorListener);
this.listener = reponseListener;
this.params = PARAMS;
}
@覆盖
保护地图<字符串,字符串> getParams()方法抛出com.android.volley.AuthFailureError {
返回PARAMS;
};
@覆盖
保护无效deliverResponse(JSONObject的响应){
listener.onResponse(响应);
}
@覆盖
受保护的响应和LT;的JSONObject> parseNetworkResponse(NetworkResponse响应){
尝试 {
字符串jsonString =新的String(response.data,
HttpHeaderParser.parseCharset(response.headers));
返回Response.success(新的JSONObject(jsonString)
HttpHeaderParser.parseCacheHeaders(响应));
}赶上(UnsupportedEncodingException E){
返回Response.error(新ParseError(e)条);
}赶上(JSONException JE){
返回Response.error(新ParseError(JE));
}
}
}
现在在我的活动我叫下面的:
字符串URL =一些有效的URL;
地图<字符串,字符串> PARAMS =新的HashMap<字符串,字符串>();
params.put(姓名,Droider);
CustomRequest jsObjRequest =新CustomRequest(Method.POST,URL,参数,可以新Response.Listener<的JSONObject>(){
@覆盖
公共无效onResponse(JSONObject的响应){
尝试 {
Log.d(回应:response.toString());
}赶上(JSONException E){
// TODO自动生成的catch块
e.printStackTrace();
}
}
},新Response.ErrorListener(){
@覆盖
公共无效onErrorResponse(VolleyError响应){
Log.d(回应:response.toString());
}
});
。AppController.getInstance()addToRequestQueue(jsObjRequest);
我的PHP code是如下:
< PHP
$名称= $ _ POST [名称];
$ J =阵列(名称=> $名);
回声json_en code($ j)条;
?>
现在它返回正确的值:
Droider
有很多的问题我自己,试试这个!
公共类CustomRequest扩展请求<的JSONObject> {
私人听者LT;的JSONObject>侦听器;
私人地图<字符串,字符串> PARAMS;
公共CustomRequest(字符串URL,地图<字符串,字符串>参数,可以收听LT;的JSONObject> responseListener,ErrorListener errorListener){
超(Method.GET,网址,errorListener);
this.listener = responseListener;
this.params = PARAMS;
}
公共CustomRequest(INT方法,字符串URL,地图<字符串,字符串>参数,可以收听LT;的JSONObject> reponseListener,ErrorListener errorListener){
超(方法,URL,errorListener);
this.listener = reponseListener;
this.params = PARAMS;
}
@覆盖
保护地图<字符串,字符串> getParams()方法抛出com.android.volley.AuthFailureError {
返回PARAMS;
};
@覆盖
受保护的响应和LT;的JSONObject> parseNetworkResponse(NetworkResponse响应){
尝试 {
字符串jsonString =新的String(response.data,HttpHeaderParser.parseCharset(response.headers));
返回Response.success(新的JSONObject(jsonString),HttpHeaderParser.parseCacheHeaders(响应));
}赶上(UnsupportedEncodingException E){
返回Response.error(新ParseError(e)条);
}赶上(JSONException JE){
返回Response.error(新ParseError(JE));
}
}
@覆盖
保护无效deliverResponse(JSONObject的响应){
listener.onResponse(响应);
}
PHP
$用户名= $ _ POST [用户名];
$密码= $ _ POST [密码];
回声json_en code($响应);
您必须做出一个地图,地图支持键值的类型,而且比你用后凌空。 在PHP中,你得到$变量= $ _ POST [key_from_map]中检索它在$变量值 然后,你建立的响应和json_en code吧。
下面是如何查询SQL和答案后回JSON作为一个PHP的例子
$回应[设备] =阵列();
而($行= mysqli_fetch_array($结果)){
$设备[ID] = $行[ID];
$设备[型] = $行[型];
array_push($响应[设备],$设备);
}
$响应[成功] =真;
回声json_en code($响应);
您可以在这里看到,响应类型的JSONObject
公共CustomRequest(INT方法,字符串URL,地图<字符串,字符串>参数,可以收听LT;的JSONObject> reponseListener,ErrorListener errorListener)
看听者的参数!
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.
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.
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.
And also how do I check if volley is really sending a JSON object?
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
$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');
The Result
null
EDIT (The correct way thanks to Georgian Benetatos)
I created the class as you mentioned the class name is CustomRequest
which is as follows:
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
$name = $_POST["name"];
$j = array('name' =>$name);
echo json_encode($j);
?>
Now its returning the correct value:
Droider
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
$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.
Here is a php example of how to query sql and post answer back as 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
public CustomRequest(int method, String url,Map<String, String> params, Listener<JSONObject> reponseListener, ErrorListener errorListener)
Look at the listener's parameter!
这篇关于发送POST请求使用截击和接收PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!