You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android通过API传数据至Python Flask(Restless API)失败及展示问题咨询

Hey there! Let's tackle your two questions one by one—first walking through the full flow of submitting data from Android to your Flask-Restless API and displaying it in a web interface, then troubleshooting why your data isn't inserting right now.

1. End-to-End Flow: Android → Flask-Restless API → Web Interface

Step 1: Set Up Your Flask-Restless API

First, install the required packages:

pip install flask flask-sqlalchemy flask-restless

Here's a minimal working example for your Flask app:

from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_restless import APIManager

app = Flask(__name__)
# Use SQLite for simplicity; replace with your preferred DB in production
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///submitted_data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

# Define your data model (matches the data you want to submit from Android)
class SubmittedRecord(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100))
    content = db.Column(db.Text)

# Create database tables (run once)
with app.app_context():
    db.create_all()

# Initialize Restless API manager and create endpoints
manager = APIManager(app, flask_sqlalchemy_db=db)
# Enable POST (create data) and GET (fetch data) methods
manager.create_api(SubmittedRecord, methods=['GET', 'POST'])

# Web route to display all submitted data
@app.route('/')
def display_data():
    all_records = SubmittedRecord.query.all()
    return render_template('data_display.html', records=all_records)

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')  # host=0.0.0.0 allows access from local network

Step 2: Android Code to Submit Data

We'll use OkHttp (a popular HTTP client) to send JSON data to your API.

First, add the OkHttp dependency to your app-level build.gradle:

implementation 'com.squareup.okhttp3:okhttp:4.12.0'

Then, here's the code to send a POST request:

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import java.io.IOException;

// Inside your Activity/Fragment
public void submitDataToAPI() {
    OkHttpClient client = new OkHttpClient();
    MediaType JSON = MediaType.get("application/json; charset=utf-8");

    // Match this JSON structure to your Flask model's fields
    String jsonPayload = "{\"title\":\"Android Test\", \"content\":\"This is data from my Android app\"}";
    RequestBody body = RequestBody.create(jsonPayload, JSON);

    // Replace with your Flask server's local IP (e.g., 192.168.1.105:5000)
    // Don't use localhost - Android emulator's localhost points to itself, not your computer
    Request request = new Request.Builder()
            .url("http://192.168.1.105:5000/api/submittedrecord")
            .post(body)
            .build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
            // Handle request failure (e.g., no internet, server down)
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (response.isSuccessful()) {
                // Data submitted successfully!
                runOnUiThread(() -> {
                    // Update UI if needed
                });
            } else {
                // Log error details to debug
                String errorMsg = response.code() + ": " + response.message();
                // Handle error (e.g., invalid data, API endpoint wrong)
            }
        }
    });
}

Critical Android Setup Notes:

  • Add internet permission to AndroidManifest.xml:
    <uses-permission android:name="android.permission.INTERNET" />
    
  • For Android 9+, allow cleartext HTTP (since Flask uses HTTP by default):
    Create res/xml/network_security_config.xml:
    <?xml version="1.0" encoding="utf-8"?>
    <network-security-config>
        <base-config cleartextTrafficPermitted="true" />
    </network-security-config>
    
    Then add to your AndroidManifest.xml's <application> tag:
    android:networkSecurityConfig="@xml/network_security_config"
    

Step 3: Web Interface to Display Data

Create a templates folder in your Flask project, then add data_display.html:

<!DOCTYPE html>
<html>
<head>
    <title>Submitted Data</title>
    <style>
        .record { border: 1px solid #ddd; padding: 10px; margin: 10px 0; border-radius: 4px; }
    </style>
</head>
<body>
    <h1>Data Submitted from Android</h1>
    {% if records %}
        {% for record in records %}
            <div class="record">
                <h3>{{ record.title }}</h3>
                <p>{{ record.content }}</p>
                <small>ID: {{ record.id }}</small>
            </div>
        {% endfor %}
    {% else %}
        <p>No data submitted yet!</p>
    {% endif %}
</body>
</html>
2. Troubleshooting: Why Android Can't Insert Data to Your API

Let's go through the most common issues step by step:

1. CORS (Cross-Origin Resource Sharing) Block

Flask-Restless doesn't handle CORS by default, so your Android request might be blocked. Fix this with flask-cors:

pip install flask-cors

Add this to your Flask code:

from flask_cors import CORS
CORS(app)  # Allows all origins (restrict to your Android app's domain in production)

2. Wrong API Endpoint URL

Flask-Restless auto-generates endpoints as /api/<lowercase_model_name>. For our SubmittedRecord model, it's /api/submittedrecord—double-check your Android code uses the exact path. Also:

  • Use your computer's local LAN IP (not localhost) in the Android URL. Find it via ipconfig (Windows) or ifconfig (macOS/Linux).
  • Ensure Flask is running with host='0.0.0.0' so it's accessible from other devices on the network.

3. Invalid Request Format

  • Flask-Restless requires Content-Type: application/json in your POST request. Make sure your Android code sets this correctly (the OkHttp example above does this).
  • Double-check your JSON payload matches the model's field names (case-sensitive!). If your model has title, don't use Title in the JSON.

4. Flask Server Issues

  • Check if your Flask server is running without errors. Look at the console logs for any tracebacks (e.g., database connection issues, model errors).
  • Test the API directly with a tool like Postman: send a POST request to http://your-ip:5000/api/submittedrecord with the same JSON payload. If this fails, the issue is with your Flask setup, not Android.

5. Database Table Not Created

Ensure db.create_all() ran successfully. You can verify by checking if submitted_data.db was created in your project folder. If not, run this manually in a Flask shell:

from your_app_file import app, db, SubmittedRecord
with app.app_context():
    db.create_all()

6. Android Network Restrictions

  • Confirm your Android device/emulator is connected to the same Wi-Fi network as your Flask server.
  • Check if any firewalls on your computer are blocking port 5000.

内容的提问来源于stack exchange,提问作者jyothi reddy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:58:00