大概流程
- 安装flask,新建并运行一个本地服务器
- 测试服务器
- 写Android接口,使用OKhttp进行数据传输
手机端:(效果展示)
服务器端:
安装flask:pip install flask
新建并运行服务器:
# coding="utf-8"
from flask import Flask, request, render_template
# create a MyFlask app
app = Flask(__name__)
@app.route("/")
def index():
return "Hello world !"
@app.route("/feedback", methods=['POST'])
def feedback():
strs = request.form["feedback"]
print(f'strs: {strs}')
return '0'
if __name__ == '__main__':
# 默认访问:http://127.0.0.1:8888/
app.run(debug=True, host='0.0.0.0', port=8888)
查看局域网IP:在命令行输入ipconfig
电脑浏览器访问:(记得关闭防火墙)
手机访问:
Android 接口
添加权限:<uses-permission android:name="android.permission.INTERNET"/>
添加OKhttp依赖:implementation"com.squareup.okhttp3:okhttp:4.5.0"
/**
* 提交按钮
*/
buttonDone.setOnClickListener {
editText.apply {
// 这里将context和edit对象传过去
RemoteServer().postString(requireContext(), this)
}
}
远程服务类
package com.ydduong.gsa.util
import android.content.Context
import android.util.Log
import android.widget.EditText
import android.widget.Toast
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import okhttp3.*
import java.io.IOException
class RemoteServer {
/**
* Feedback页面提向服务器交反馈信息
*/
fun postString(context: Context, editText: EditText) {
// 网址
val url = "http://192.168.1.102:8888/feedback"
// 表单
val formBody = FormBody.Builder().apply {
add("feedback", editText.text.toString())
}.build()
// 请求
val request = Request.Builder().url(url).post(formBody).build()
// http
OkHttpClient().newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
MainScope().launch {
Toast.makeText(context, "服务器错误,请稍后再试", Toast.LENGTH_LONG).show()
}
}
override fun onResponse(call: Call, response: Response) {
Log.v("httpLog code", response.code.toString())
Log.v("httpLog message", response.message)
Log.v("httpLog body", response.body.toString())
MainScope().launch {
if (response.code == 200) {
Toast.makeText(context, "提交成功", Toast.LENGTH_LONG).show()
editText.text.clear()
} else {
Toast.makeText(context, "提交失败,错误代码${response.code}", Toast.LENGTH_LONG).show()
}
}
}
})
}
}
注:Android 9 之后默认不支持http,可以向application添加属性android:usesCleartextTraffic="true"
解决
<application
android:allowBackup="true"
android:icon="@drawable/ic_app_icon_5"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
<!--here here-->
android:usesCleartextTraffic="true"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>