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

无需数据库实现Android与Flask服务器文件传输及结果返回的方法

无需数据库实现Android与Flask的文本处理交互

完全可以不用数据库实现这个功能,所有数据都在请求响应的内存流转中完成,不需要持久化存储。下面是具体的代码修改方案:

Flask服务器端修改

修改原有的/upload_file接口,增加内容处理逻辑,处理完成后直接返回结果:

import io
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/upload_file', methods=['POST'])
def receive_and_process_file():
    # 接收Android端传来的文本内容,对应Android端的参数名"fileContent"
    file_content = request.form.get('fileContent', '')
    
    # --------------------------
    # 这里替换为你的实际文本处理逻辑,示例:将所有字母转为大写
    processed_content = file_content.upper()
    # --------------------------
    
    # 返回结构化处理结果,方便Android端解析
    return jsonify({
        'status': 'success',
        'processed_content': processed_content
    }), 200

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=12345, debug=True)

修改说明:

  • 原代码直接返回原内容,现在改为接收表单参数fileContent(与Android端请求参数对应)
  • 加入自定义文本处理逻辑(示例为大写转换,可按需替换)
  • 用jsonify返回JSON格式结果,便于Android端解析

Android客户端修改

修改sendToServer方法,增加响应结果的接收与处理,同时修正请求URL指向正确的Flask接口:

import org.json.JSONObject;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.MultipartBody;

public class socket_test extends AppCompatActivity {

    private TextView textView;

    // 真机测试时,127.0.0.1要换成运行Flask的电脑局域网IP,比如192.168.x.x
    private static final String SERVER_URL = "http://127.0.0.1:12345/upload_file";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file);
        textView = findViewById(R.id.FileName); // 用于显示处理结果的TextView
    }

    public void selectFile(View view) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("text/plain");
        startActivityForResult(intent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1 && resultCode == RESULT_OK) {
            try {
                InputStream inputStream = getContentResolver().openInputStream(data.getData());
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder stringBuilder = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line).append("\n"); // 保留换行符,避免内容格式丢失
                }

                inputStream.close();
                String fileContent = stringBuilder.toString();

                // 发送内容到服务器并接收处理结果
                sendToServer(fileContent);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void sendToServer(String fileContent) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = new MultipartBody.Builder()
                            .setType(MultipartBody.FORM)
                            .addFormDataPart("fileContent", fileContent)
                            .build();

                    Request request = new Request.Builder()
                            .url(SERVER_URL)
                            .post(requestBody)
                            .build();

                    Response response = client.newCall(request).execute();
                    if (!response.isSuccessful()) {
                        throw new IOException("请求失败: " + response.code());
                    }

                    // 解析服务器返回的JSON结果
                    String responseBody = response.body().string();
                    JSONObject jsonObject = new JSONObject(responseBody);
                    String processedContent = jsonObject.getString("processed_content");

                    // 在UI线程更新界面,避免子线程操作UI报错
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            textView.setText(processedContent);
                            // 也可以跳转到output页面传递处理后的结果
                            Intent intent = new Intent(socket_test.this, output.class);
                            intent.putExtra("processedContent", processedContent);
                            startActivity(intent);
                        }
                    });

                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                    // 异常时在UI线程提示错误
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            textView.setText("处理失败,请检查服务器连接");
                        }
                    });
                }
            }
        }).start();
    }
}

修改说明:

  • 修正SERVER_URL指向Flask的/upload_file接口
  • 读取文件时保留换行符,避免内容格式丢失
  • 新增服务器响应解析逻辑,获取处理后的内容
  • 通过runOnUiThread在UI线程更新界面或跳转页面,规避子线程操作UI的错误
  • 增加异常处理,提升稳定性

关键注意事项:

  1. 真机测试时,SERVER_URL中的127.0.0.1要替换为运行Flask服务器的电脑局域网IP(如192.168.1.100),且手机与电脑需在同一局域网
  2. AndroidManifest.xml中必须添加网络权限:<uses-permission android:name="android.permission.INTERNET" />
  3. Android 9及以上需允许明文HTTP请求,可在application标签添加android:usesCleartextTraffic="true"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 02:32:42