![](/img/trans.png)
[英]Android Studio error org.apache.http.conn.HttpHostConnectException: Connection to http://10.0.2.2:8080 refused
[英]unable to upload image from android to python flask server, show the error org.apache.http.conn.HttpHostConnectException in android
我正在使用 Multipartentity 将图像上传到 python 服务器。 我收到一个错误是来自服务器的响应:org.apache.http.conn.HttpHostConnectException:连接到http://192.168.0.104:5000 被拒绝。 可以解释任何人,为什么会出现错误?
这是后端任务代码:
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
long totalSize = 0;
ProgressDialog progressDialog;
@Override
protected void onPreExecute() {
// setting progress bar to zero
progressDialog = new ProgressDialog(RegisterActivity.this);
progressDialog.show();
}
@Override
protected String doInBackground(Void... params) {
return uploadFile();
}
@SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
@Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
String imagefilepath = null;
String filemanagerstring = filePath.getPath();;
String selectedImagePath = getPath(filePath);
if (selectedImagePath != null) {
imagefilepath = selectedImagePath;
} else if (filemanagerstring != null) {
imagefilepath = filemanagerstring;
} else {
Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}
File sourceFile = new File(imagefilepath);
// Adding file data to http body
entity.addPart("aadharimage", new FileBody(sourceFile));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
@Override
protected void onPostExecute(String result) {
Log.e(TAG, "Response from server: " + result);
progressDialog.dismiss();
// showing the server response in an alert dialog
super.onPostExecute(result);
}
}
这是网址
公共字符串 UPLOAD_URL = " http://192.168.0.104:5000/static/android ";
这是phyton代码
@app.route('/static/android', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['aadharimage']
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file :
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
但你写的额外代码是,
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'],
filename)
你为什么写这段代码。 上传图片是否需要此代码?
我从 java 和 android 中忘记了很多,但错误可能来自最后一行的flask函数
return redirect(url_for('upload_file', filename=filename))
您正在重定向到相同的 URL 并且它没有文件名参数
在检查flask doc关于上传文件后,您需要添加另一种下载上传文件的方法并重定向到该方法
从文档中检查:
现在缺少最后一件事:上传文件的服务。 在upload_file()中,我们将用户重定向到url_for('uploaded_file', filename=filename),即/uploads/filename。 所以我们编写了uploaded_file() 函数来返回该名称的文件。 从 Flask 0.5 开始,我们可以使用一个为我们做这件事的函数:
并将 upload_file 方法的最后一行更改为:
return redirect(url_for('uploaded_file', filename=filename))
并创建上传文件的方法:
from flask import send_from_directory
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'],
filename)
解决方案2:
或者,如果您只需要将图像保存在烧瓶服务器中,您可以向用户返回一条成功消息,说明图像已保存。
将您的python代码更改为:
@app.route('/static/android', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
print request
print request.values
# check if the post request has the file part
if 'file' not in request.files:
# flash('No file part')
return redirect(request.url)
print(request.files['aadharimage'])
file = request.files['aadharimage']
# if user does not select file, browser also
# submit a empty part without filename
if file.filename == '':
print(file)
# flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
print(file)
print(file.filename)
filename = secure_filename(file.filename)
# print filename
print(app.config['UPLOAD_FOLDER'])
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return "an image has been saved "
这仅适用于python部分
还要确保您的烧瓶应用程序在 192.168.0.104 和端口 5000 上运行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.