0

I'm trying to make a POST request to an api that I have created in Visual Studio. The api works, and I finally managed to find some code that allows me to connect to it (and it's not deprecated). The problem is that this code was made for a GET request while I need to make a POST. I created two boxes where I insert the data I want to pass (utente, password) and I created a button that takes the data from the boxex and convert them to string.

I tried already searching a lot of examples and tutorials that show how to make a POST request but the majority are very old and doesn't work anymore in Android Studio, or at least I can't make them work.

Now, this is the function that should be sending the data, I haven't touched the code since I don't really know what to modify except for the Request Method.

private StringRequest searchNameStringRequest(String utente, String password)
    {
        String url = "http://192.168.1.11:57279/api/utente";
        return new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>()
                {
                    @Override
                    public void onResponse(String response)
                    {
                        try
                        {
                            JSONObject result = new JSONObject(response).getJSONObject("list");
                            int maxItems = result.getInt("end");
                            JSONArray resultList = result.getJSONArray("item");
                        }
                        catch (JSONException e)
                        {
                            Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    }
                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error)
                    {
                        Toast.makeText(MainActivity.this, "Food source is not responding (USDA API)", Toast.LENGTH_LONG).show();
                    }
                });
    }

Can someone explain me how to take the data and send it like a JSON Object that has

keys = user, password

values = utente, password (the values are from the two boxes mentioned before)

Thank to anyone who is willing to help me and I hope that asking for so much help isn't against the site rules.

I'm using Volley since is not so complicated and because it seems to work.

Using the GET method it show me the existing json with message cannot be converted to JSON object (I don't care about that, it's just a confirmation that it connects to the api)

Using the POST method it throws the ErrorResponse at the end (Food source is not responding)

EDIT: Added OnCreate method since I need a StringRequest return

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        queue = Volley.newRequestQueue(this);
        Button invia = findViewById(R.id.submit);
        final EditText utenteInserito = findViewById(R.id.utente);
        final EditText passwordInserito = findViewById(R.id.password);

        invia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String utente = utenteInserito.getText().toString();
                String password = passwordInserito.getText().toString();
                queue.cancelAll(R.id.submit);
                StringRequest stringRequest = searchNameStringRequest(utente, password);
                stringRequest.setTag(R.id.submit);
                queue.add(stringRequest);
            }
        });
    }

EDIT: I have followed the suggested answer given but it doesn't seem to work

The resulting code is shown below but I get the OnErrorResponse, I don't think it's a problem with the api because trying with a GET response it gives me the exiting json array, so I think it's a problem with the code.

private StringRequest searchNameStringRequest(final String utente, final String password)
    {
        String url = "http://192.168.1.11:57279/api/utente";
        StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>()
        {
            @Override
            public void onResponse(String response)
            {
                System.out.println(response);
            }
        }, new Response.ErrorListener()
        {

            @Override
            public void onErrorResponse(VolleyError error)
            {
                Toast.makeText(MainActivity.this,"Service Unavailable",Toast.LENGTH_SHORT).show();
                error.printStackTrace();
            }
        })
        {
            @Override
            protected Map<String, String> getParams()
            {
                Map<String,String> map = new HashMap<>();
                map.put("user", utente.trim());
                map.put("password",password.trim());
                return map;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
        requestQueue.add(request);
        return request;
    }
Adrian
  • 121
  • 1
  • 9
  • 3
    Possible duplicate of [Volley - POST/GET parameters](https://stackoverflow.com/questions/16626032/volley-post-get-parameters) – Saltae Mar 23 '19 at 12:14

3 Answers3

1

It's working following this question:

How to send a POST request using volley with string body?

Thanks to you all for your interest.

Adrian
  • 121
  • 1
  • 9
0
        String url = "your url";
    StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            System.out.println(response);
            dialog.dismiss();
            try {
// your logic when API sends your some data
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dialog.dismiss();
                Toast.makeText(context,"Service Unavailable",Toast.LENGTH_SHORT).show();
                error.printStackTrace();
            }
        }){
//This is how you will send the data to API
            @Override
            protected Map<String, String> getParams(){
                Map<String,String> map = new HashMap<>();
                map.put("name",username.getText().toString());
                map.put("password",password.getText().toString());
                return map;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
        requestQueue.add(request);
    }
mDeveloper
  • 122
  • 9
0

Here is a nice tutorial, I have tried it and it worked seamlessly.

Android Login and Registration with PHP, MySQL and SQLite

You can skip the sqlite and the phpMyAdmin part.

  • Thank you for your answer, I managed to fix it following this question: https://stackoverflow.com/questions/33573803/how-to-send-a-post-request-using-volley-with-string-body – Adrian Mar 25 '19 at 10:53