Post Request does not pass `getParams()`meters with Volley’s Stringrequest

Asked

Viewed 22 times

0

When I make a POST Request according to my function postRequest() using the StringRequest of Volley I cannot access the parameters passed on getParams(). However, the method getRequest() works as expected. I’m running the app on my phone, talking to the server on my notebook, both connected on the same wifi.

My Mainactivity is:

package com.example.simplerequest;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button get_request = (Button) findViewById(R.id.getRequest);
        textView = (TextView) findViewById(R.id.textView);

        get_request.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                postRequest(); // ou getRequest();
            }
        });
    }

    private void getRequest () {
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        String url="http://192.168.5.199:5000/get_all";
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                textView.setText("Data: " + response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                textView.setText("Get Data: Response Failed!"+error);
            }
        }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String,String> params = new HashMap<String,String>();
                params.put("Content-Type", "application/json; charset=UTF-8");
                params.put("x-api-key", "mySuperSecretKey");
                return params;
            }
        };

        requestQueue.add(stringRequest);
    }

    private void postRequest() {
        String url="http://192.168.5.199:5000/add_new";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                textView.setText("Post Data: " + response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                textView.setText("Post Data: Response Failed!\n"+error);
            }
        }){
            @Override
            protected Map<String, String> getParams() {
                Map<String,String> params = new HashMap<String,String>();
                params.put("id", "3");
                params.put("name", "value3");
                return params;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String,String> header = new HashMap<String,String>();
                header.put("Content-Type", "application/json; charset=UTF-8");
                header.put("x-api-key", "mySuperSecretKey");
                return header;
            }
        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.getCache().clear();
        requestQueue.add(stringRequest);
    }
}

And, when triggering the function postRequest(), my app returns Post Data: {"error":"Bad request"}. The request is sent successfully and does not fall into the onErrorResponse.

However, I cannot access the meter on the side of my server, which answers me:

Params: {}
192.168.5.94 - - [03/Nov/2020 04:21:56] "POST /add_new HTTP/1.1" 200 -

My server, made with flask, is:

from flask import Flask, request, jsonify

app = Flask(__name__)

db = [
        {
            'id':1,
            'name':'value1',
        },
        {
            'id':2,
            'name':'value2',
        }
    ]

@app.route('/get_all', methods=['GET'])
def get_all():
    if request.headers.get('x-api-key') != 'mySuperSecretKey':
        return jsonify({'error': 'Permission denied'}), 403
    return jsonify(db), 200

@app.route('/add_new', methods=['POST'])
def add_new():
    if request.headers.get('x-api-key') != 'mySuperSecretKey':
        return jsonify({'error': 'Permission denied'}), 403

    print("\nParams: {}".format(request.args.to_dict()))
    
    if ("id" in request.args.keys()) and ("name" in request.args.keys()):
        db.append({
            'id': int(request.args.get('id')),
            'name': request.args.get('name')
        })
        return jsonify(db), 200
    
    return jsonify({'error': 'Bad request'}), 200 #O postRequest() recebe este return
      
if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)

And when I test the routes with the following Python script:

import requests

url = "http://127.0.0.1:5000/"
url = "http://192.168.5.199:5000/"

headers = {
    'content-type' : 'application/json',
    'x-api-key':'mySuperSecretKey'
    }

r = requests.get(url+'get_all', headers=headers)
print(r.json())

input_data = {
    'id':"3",
    'name':'value3',
}
r = requests.post(url+'add_new', headers=headers, params=input_data)
print(r.json())

I see that the output of the script is the expected:

[{'id': 1, 'name': 'value1'}, {'id': 2, 'name': 'value2'}]
[{'id': 1, 'name': 'value1'}, {'id': 2, 'name': 'value2'}, {'id': 3, 'name': 'value3'}]

And the server terminal output too:

192.168.5.199 - - [03/Nov/2020 04:17:05] "GET /get_all HTTP/1.1" 200 -

Params: {'id': '3', 'name': 'value3'}
192.168.5.199 - - [03/Nov/2020 04:17:05] "POST /add_new?id=3&name=value3 HTTP/1.1" 200 -

Basically, the Python script generates the request /add_new?id=3&name=value3, while my app generates /add_new.

I added a Log.d(...) within the function getParams() and saw that she is called.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.