android客户端通过OkHttp传递给服务器三个参数,服务器端如何用flask接收这些参数,并查询mysql得到一个查询结果,返回客户端一个list,客户端如何接收这个list,请给出代码
时间: 2023-06-03 16:04:24 浏览: 86
Android客户端与服务器端交互(okHttp)
4星 · 用户满意度95%
好的,我了解了您的要求。以下是示例代码:
客户端代码:
OkHttpClient client = new OkHttpClient();
String url = "http://yourserver.com/query";
Request request = new Request.Builder()
.url(url)
.post(RequestBody.create(MediaType.parse("application/json"), "{\"param1\":\"value1\",\"param2\":\"value2\",\"param3\":\"value3\"}"))
.build();
Response response = client.newCall(request).execute();
String responseBody = response.body().string();
List<String> resultList = new Gson().fromJson(responseBody, new TypeToken<List<String>>() {}.getType());
服务器端代码:
from flask import Flask, request, jsonify
import pymysql
app = Flask(__name__)
@app.route('/query', methods=['POST'])
def query():
try:
data = request.get_json()
param1 = data.get('param1')
param2 = data.get('param2')
param3 = data.get('param3')
# 连接MySQL数据库
conn = pymysql.connect(host='localhost', port=3306, user='yourusername', passwd='yourpassword', db='yourdatabase')
cursor = conn.cursor()
# 执行查询
cursor.execute(f"SELECT * FROM yourtable WHERE col1='{param1}' AND col2='{param2}' AND col3='{param3}'")
result = cursor.fetchall()
# 关闭连接
cursor.close()
conn.close()
return jsonify(result)
except:
return jsonify([])
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80)
请注意,以上代码示例仅供参考,具体实现方式可能会因为不同的具体情况而有所不同。
阅读全文