0

API route in Python (Flask)

@app.route('/secret')
def secret():
    if request.get_json(force=True)['key'] == 'secret key':
        return jsonify(msg='Hello!')

It is working linux terminal

curl -iX GET -d '{"key":"secret key"}' localhost

Linux terminal output this

{"msg":"Hello!"}

It doesn't need to work in browser.

try{
    HttpURLConnection connection = (HttpURLConnection)
                        new URL("http://<my local ip>/secret").openConnection();
    connection.setRequestMethod("GET");
    connection.setDoOutput(true);
    connection.connect();
    JSONObject jsonInput = new JSONObject();
    jsonInput.put("key", "secret key");
    OutputStream os = connection.getOutputStream();
    byte[] input = jsonInput.toString().getBytes(StandardCharsets.UTF_8);
    os.write(input, 0, input.length);
    os.flush();
    os.close();
    BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    StringBuilder response = new StringBuilder();
    String responseLine = null;
    while ((responseLine = br.readLine()) != null) {
        response.append(responseLine.trim());
    }
    return response.toString();
} catch (IOException | JSONException e) {
    Log.e("MainActivity", "Error: " + e.getMessage());
}

Although the GET method is set to the connection request in my codes, a POST request is being sent to the Python server.

Python Interpreter

Is it impossible to fix this?

1 Answers1

0

Request Body is not recommended in HTTP GET requests. See HERE

A payload within a GET request message has no defined semantics; sending a payload body on a GET request might cause some existing implementations to reject the request.

When you try to write on a URL, you are implicitly POSTing on it despite you had set GET as the HTTP method. At below lines:

OutputStream os = connection.getOutputStream();
byte[] input = jsonInput.toString().getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);

For confirmation of my words see Writing to a URLConnection

writing to a URL is often called posting to a URL. The server recognizes the POST request and reads the data sent from the client.

A Farmanbar
  • 4,381
  • 5
  • 24
  • 42