所以我看到这个代码从这个论坛:连接Java与Python Flask
from flask import Flask, jsonify, request
import json
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
@app.route('/add/', methods = ['POST'])
def add_numbers():
if request.method == 'POST':
decoded_data = request.data.decode('utf-8')
params = json.loads(decoded_data)
return jsonify({'sum': params['x'] + params['y']})
if __name__ == '__main__':
app.run(debug=True)
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class PostClass {
public static void main(String args[]){
HttpURLConnection conn = null;
DataOutputStream os = null;
try{
URL url = new URL("http://127.0.0.1:5000/add/"); //important to add the trailing slash after add
String[] inputData = {"{"x": 5, "y": 8, "text":"random text"}",
"{"x":5, "y":14, "text":"testing"}"};
for(String input: inputData){
byte[] postData = input.getBytes(StandardCharsets.UTF_8);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty( "charset", "utf-8");
conn.setRequestProperty("Content-Length", Integer.toString(input.length()));
os = new DataOutputStream(conn.getOutputStream());
os.write(postData);
os.flush();
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}finally
{
if(conn != null)
{
conn.disconnect();
}
}
}
}
它展示了如何将变量从java传递到python,然后从python返回json结果。我想知道的是你如何做一些类似的文件图像,以便python可以使用flask.request。文件['请求来自java']。我需要将文件图像发送给python,以便python使用机器学习来预测图像。请协助。抱歉,如果这个问题听起来很蹩脚。我只有6个月的经验。这是python代码从我的android工作室接收响应。我想从我的春季启动实现相同的请求,以便我将使用相同的python,可以从android和java接收请求。
@app.route('/', methods=['GET', 'POST'])
def handle_request():
imagefile = flask.request.files['image']
# to extract file name
filename = werkzeug.utils.secure_filename(imagefile.filename)
print("nReceived image File name: " + imagefile.filename)
imagefile.save(filename)
imageML = load_img('androidFlask.jpg', color_mode='rgb', target_size= (224,224))
imageArray = img_to_array(imageML)
imageArray = np.expand_dims(imageArray, axis = 0)
imageArray = imageArray/255.0
prediction = breedModel.predict(imageArray)
predicted_class = np.argmax(np.round(prediction), axis = 1)
result = str(label_mapping[predicted_class[0]])
result = result.replace("_", " ")
return result
app.run(host="0.0.0.0", port=5000, debug=True)
对于那些和我有类似问题的人,你可以看看这篇文章。使用POST和HttpURLConnection发送文件这似乎能解决我的问题。