Flask--学习笔记-与Android的交互

来源:互联网 发布:jquery 1.7.1.min.js 编辑:程序博客网 时间:2024/06/10 14:05
  • 服务器后台添加一个API接口用于接收Android端数据,具体写法跟从WEB端接收表单字段相同
  • Android端模拟Form表单向上边的接口POST数据

Android端的核心代码

private void uploadFileAndString(String actionUrl, String newName, File uploadFile) {    String end = "\r\n";    String twoHyphens = "--";    String boundary = "*****";    try {        URL url = new URL(actionUrl);        HttpURLConnection con = (HttpURLConnection) url.openConnection();        /* 允许Input、Output,不使用Cache */        con.setDoInput(true);        con.setDoOutput(true);        con.setUseCaches(false);        /* 设置传送的method=POST */        con.setRequestMethod("POST");        /* setRequestProperty */        con.setRequestProperty("Connection", "Keep-Alive");        con.setRequestProperty("Charset", "UTF-8");        con.setRequestProperty("Content-Type",                "multipart/form-data;boundary=" + boundary);        /* 设置DataOutputStream */        DataOutputStream ds = new DataOutputStream(con.getOutputStream());        ds.writeBytes(twoHyphens + boundary + end);        ds.writeBytes("Content-Disposition: form-data; "                + "name=\"userfile\";filename=\"" + newName + "\"" + end);        ds.writeBytes(end);        /* 取得文件的FileInputStream */        FileInputStream fStream = new FileInputStream(uploadFile);        /* 设置每次写入1024bytes */        int bufferSize = 1024;        byte[] buffer = new byte[bufferSize];        int length = -1;        /* 从文件读取数据至缓冲区 */        while ((length = fStream.read(buffer)) != -1) {            /* 将资料写入DataOutputStream中 */            ds.write(buffer, 0, length);        }        ds.writeBytes(end);        // -----        ds.writeBytes(twoHyphens + boundary + end);        ds.writeBytes("Content-Disposition: form-data;name=\"name\"" + end);        ds.writeBytes(end + URLEncoder.encode("xiexiezhichi", "UTF-8")                + end);        // -----        ds.writeBytes(twoHyphens + boundary + twoHyphens + end);        /* close streams */        fStream.close();        ds.flush();        /* 取得Response内容 */        InputStream is = con.getInputStream();        int ch;        StringBuffer b = new StringBuffer();        while ((ch = is.read()) != -1) {            b.append((char) ch);        }        handler.sendEmptyMessage(0x12);        /* 关闭DataOutputStream */        ds.close();    } catch (Exception e) {        handler.sendEmptyMessage(0x13);    }}@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    findViewById(R.id.button3).setOnClickListener(new OnClickListener() {        @Override        public void onClick(View v) {            new Thread(new Runnable() {                @Override                public void run() {                    uploadFileAndString("http://192.168.1.130:5000/file",                            "a.jpg", new File(Environment                                    .getExternalStorageDirectory()                                    .getAbsolutePath()                                    + "/a.png"));                }            }).start();        }    });}

Flask服务器端代码

@app.route('/file', methods=['POST', 'GET'])def update_file():    """    Api for getting file & string data from MApp    Store data to local files    """    if request.method == 'POST':        # Get file object from field of file        f = request.files['userfile']        f.save(os.path.join('/home/ping/Documents', f.filename))        # Get str object from field of text        s = request.form['name']        with open('/home/ping/Documents/test.txt', 'a') as f:            f.write(s)    return 'Done!'
0 0