使用Volley发送post请求并以PHP格式接收

我试图在我的项目中使用volley来处理我的所有HTTP请求,因为据我所知它是最有效的。 所以我开始通过AndroidHive教程学习排球。

我的第一个GET请求成功了。 然后我转到POST请求,但我失败了。 我在Stack Overflow上看到很多人在将截击请求与PHP结合起来时遇到了问题。 我相信我们无法使用$_POST[""]的常规方式访问它,因为齐射将JSON对象发送到我们指定的URL。

我尝试了许多解决方案,但没有成功。 我想应该有一个简单而标准的方法来使用PHP的凌空。 所以我想知道在我的PHP代码中接收volley发送的json对象需要做什么。

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

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

 JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST, url, null, new Response.Listener() { @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 getParams() { Map params = new HashMap(); params.put("name", "Droider"); return params; } }; // Adding request to request queue AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj); 

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

  

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

结果

 null 

编辑(感谢Georgian Benetatos的正确方法)

我提到类的名称是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{ private Listener listener; private Map params; public CustomRequest(String url, Map params, Listener reponseListener, ErrorListener errorListener) { super(Method.GET, url, errorListener); this.listener = reponseListener; this.params = params; } public CustomRequest(int method, String url, Map params, Listener reponseListener, ErrorListener errorListener) { super(method, url, errorListener); this.listener = reponseListener; this.params = params; } @Override protected Map getParams() throws com.android.volley.AuthFailureError { return params; }; @Override protected void deliverResponse(JSONObject response) { listener.onResponse(response); } @Override protected Response 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 params = new HashMap(); params.put("name", "Droider"); CustomRequest jsObjRequest = new CustomRequest(Method.POST, url, params, new Response.Listener() { @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代码如下:

 $name); echo json_encode($j); ?> 

现在它返回正确的值:

 Droider 

Solutions Collecting From Web of "使用Volley发送post请求并以PHP格式接收"

我自己遇到很多问题,试试吧!

 public class CustomRequest extends Request { private Listener listener; private Map params; public CustomRequest(String url,Map params, Listener responseListener, ErrorListener errorListener) { super(Method.GET, url, errorListener); this.listener = responseListener; this.params = params; } public CustomRequest(int method, String url,Map params, Listener reponseListener, ErrorListener errorListener) { super(method, url, errorListener); this.listener = reponseListener; this.params = params; } @Override protected Map getParams() throws com.android.volley.AuthFailureError { return params; }; @Override protected Response 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); 

你必须制作一张地图,地图支持键值types,而不是你用齐射来发布。 在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); 

您可以在此处看到响应types是JSONObject

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

看一下监听器的参数!

 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() { @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 getHeaders() throws AuthFailureError { HashMap headers = new HashMap(); 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并查看结果。

这是一个将发送请求发送到php脚本的简单代码

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() { @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 getParams(){ Map params = new HashMap(); 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

 < ?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'} } 

资料来源: Android Volley Post Request Tutorial

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

ANDROID代码:

 StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener() { @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 getParams() throws AuthFailureError { HashMap headers = new HashMap<>(); headers.put("name", "Droider"); return headers; } @Override public Priority getPriority() { return Priority.IMMEDIATE; } }; ApplicationController.getInstance().addToRequestQueue(stringRequest); 

PHP代码:

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

如果这有助于任何人,这对我来说很好

 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() { @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 getParams() { final String email = Email.getText().toString().trim(); final String password = Password.getText().toString().trim(); Map MyData = new HashMap(); MyData.put("email", email); MyData.put("password", password); return MyData; } }; } the login.php < ?php $message = $_POST["email"]; echo $message; ?>