我正在尝试使用httpclient将文件从Android应用程序上传到flask服务器。我总是从服务器获得400错误的请求错误
public String send()
{
try {
url = "http://192.168.1.2:5000/audiostream";
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "/test.pcm");
Log.d ("file" , file.getCanonicalPath());
try {
Log.d("transmission", "started");
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
ResponseHandler Rh = new BasicResponseHandler();
InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
response.getEntity().getContentLength();
StringBuilder sb = new StringBuilder();
try {
BufferedReader reader =
new BufferedReader(new InputStreamReader(response.getEntity().getContent()), 65728);
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
}
catch (IOException e) { e.printStackTrace(); }
catch (Exception e) { e.printStackTrace(); }
Log.d("Response", sb.toString());
Log.d("Response", "StatusLine : " + response.getStatusLine() + " Entity: " + response.getEntity()+ " Locate: " + response.getLocale() + " " + Rh);
return sb.toString();
} catch (Exception e) {
// show error
Log.d ("Error", e.toString());
return e.toString();
}
}
catch (Exception e)
{
Log.d ("Error", e.toString());
return e.toString();
}
}
但是当我正确使用curl文件上传时 curl -i -F filedata = @“/ home / rino / test.pcm”http://127.0.0.1:5000/audiostream 服务器配置
import os
from werkzeug.utils import secure_filename
from flask import Flask, jsonify, render_template, request, redirect, url_for, make_response, send_file, flash
app = Flask(__name__)
app.debug = True
UPLOAD_FOLDER = '/home/rino/serv'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
@app.route('/audiostream',methods=['GET', 'POST'])
def audiostream():
if request.method == 'POST':
file = request.files['filedata']
filename = secure_filename(file.filename)
fullpath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(fullpath)
return jsonify(results=['a','b'])
if request.method == 'GET':
return "it's uploading page"
if __name__ == "__main__":
app.run(host='0.0.0.0')
所以,我认为我的错误是微不足道的,但我无法认出来。
答案 0 :(得分:3)
当Flask无法访问请求中的密钥时,会抛出400 Bad Request。我的猜测(仅通过查看代码)是您尝试提取request.files['filedata']
,但它并不存在于Java请求中。
但它在卷曲请求中-F filedata
。
试着看一下:Http POST in Java (with file upload)。它显示了如何使用HttpClient和HttpPost向表单上载添加部件的示例。
根据this post,您可能需要添加" multipart / form-data"的编码类型。同样。
tl; dr - Flask正在寻找请求词典中的一个filedata键,你不会发送一个。