大概流程
- 安裝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>