问题描述
我正在尝试使用httpclient将文件从Android应用程序上传到烧瓶服务器。 我总是从服务器得到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” 服务器配置是
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')
所以,我认为我的错误是微不足道的,但我无法认出来。
1楼
当Flask无法访问请求中的密钥时,它会抛出400 Bad Request。
我的猜测(只是通过查看代码)是你试图提取request.files['filedata']
但它在Java请求中不存在。
但它在卷曲请求-F filedata
。
试着看看这个: 。 它显示了如何使用HttpClient和HttpPost向表单上载添加部件的示例。
根据您可能还需要添加“multipart / form-data”的编码类型。
tl; dr - Flask正在寻找请求词典中的一个filedata键,你不是要发送一个。