Android Volley POST request: getting GET request method on server side (php)

前端 未结 1 1659
时光说笑
时光说笑 2021-01-16 09:03

I am making an android app that needs to send Post requests to my server and could really use some help! I\'ve been trying to make these requests using android Volley. I\'ve

相关标签:
1条回答
  • 2021-01-16 09:20

    Here is code you can use to make a POST request with the Volley library in android. Assuming you import your library as such in your application build.gradle file:

    dependencies{
         .... 
         implementation 'com.android.volley:volley:1.1.0'
         .....
     }
    

    The following code can be put in a method as some routine task to perform your POST request

    String requestUrl = "http://myapi.com/api/postresource.php";
    StringRequest stringRequest = new StringRequest(Request.Method.POST, requestUrl, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.e("Volley Result", ""+response); //the response contains the result from the server, a json string or any other object returned by your server
    
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace(); //log the error resulting from the request for diagnosis/debugging
    
        }
    }){
    
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> postMap = new HashMap<>();
            postMap.put("param1", "value1");
            postMap.put("param2", value2);
            //..... Add as many key value pairs in the map as necessary for your request
            return postMap;
        }
    };
    //make the request to your server as indicated in your request url
    Volley.newRequestQueue(getContext()).add(stringRequest);
    
    0 讨论(0)
提交回复
热议问题