最近重新梳理了下Android端与Flask服务端的交互。做了以下Demo,复制粘贴基本就可用啦
Android端
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
import okhttp3.*;
OkHttpClient okHttpClient = new OkHttpClient();
File file = new File(Environment.getExternalStorageDirectory(), "the file you want to upload"); // TODO: 配置需上传文件
// RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("file", file.getName(), // TODO: 配置文件所在参数
RequestBody.create(MediaType.parse("application/octet-stream"), file))
.addFormDataPart("param1", "111") // TODO: 配置其他参数
.addFormDataPart("param2", "222") // TODO: 配置其他参数
.build();
Request request = new Request.Builder().url("http://127.0.0.1/test").post(requestBody).build(); // TODO: 配置上传地址
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d(TAG, "发送请求失败");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d(TAG, "发送请求成功");
}
});
|
服务端 使用Flask-Restful api
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
from flask import Flask, request, send_file, jsonify
from flask_restful import Resource, Api, reqparse
class Test(Resource):
def post(self):
parser = reqparse.RequestParser()
parser.add_argument('param1') # TODO: 更改获取参数
parser.add_argument('param2') # TODO: 更改获取参数
args = parser.parse_args()
content = request.files['file']
param1 = args.get('param1')
param2 = args.get('param2')
content.save('/Users/xxx/Desktop/yahaha.text') # TDOO: 更改存储文件名称
return "ok"
api.add_resource(Coverage, '/db/coverage')
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True, threaded=True)
|
参考
StackOverflow
HTTP Content-Type