使用 Volley 发送 post 请求并在 PHP 中接收 [英] Send post request using Volley and receive in PHP
问题描述
我试图在我的项目中使用 volley 来处理我所有的 HTTP 请求,因为据我所知,它是最有效的.所以我开始按照这个 AndroidHive 教程学习 volley.
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.
我的第一个 GET 请求成功了.然后我转到 POST 请求,但失败了.我在 Stack Overflow 上看到很多人在将 volley 的 post 请求与 PHP 结合使用时遇到了问题.我相信我们无法使用 $_POST[""]
的正常方式访问它,因为 volley 将 JSON 对象发送到我们指定的 URL.
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.
我尝试了很多解决方案,但都没有成功.我想应该有一种简单而标准的方式在 PHP 中使用 volley.所以我想知道我需要做什么才能在我的PHP代码中接收由volley发送的json对象.
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.
还有我如何检查 volley 是否真的在发送 JSON 对象?
And also how do I check if volley is really sending a JSON object?
我发送简单帖子请求的截击代码:
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);
我接收 json 对象的 PHP 代码:(我很确定这是错误的方式,我在 PHP 方面不是很好)
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;
?>
我也尝试了很多像这样在 PHP 中接受 JSON 对象的方法echo file_get_contents('php://input');
I tried lots of ways of accepting JSON object in PHP like this one as well
echo file_get_contents('php://input');
结果
null
编辑(正确方法感谢Georgian Benetatos)
我创建了你提到的类,类名是CustomRequest
,如下所示:
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);
我的PHP代码如下:
<?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);
你必须制作一个地图,地图支持键值类型,然后你用凌空发帖.在 php 你得到 $variable = $_POST["key_from_map"] 来检索它在 $variable 中的值然后建立响应并对其进行 json_encode.
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.
这是一个如何查询 sql 并将答案作为 JSON 回传的 php 示例
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);
这里可以看到响应类型是JSONObject
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)
看监听器的参数!
这篇关于使用 Volley 发送 post 请求并在 PHP 中接收的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!