1

So i saw this code from this forum: Connect Java with 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();
            }
        }
    }
}

It shows how to pass variables from java to python and then from python it will response back json result. What i would like to know is how do you do something similar for file image so that python can use flask.request.files['request from java']. I require to send file image to python for python to use machine learning to predict the image. Kindly assist. Sorry if the question sounds lame. I only have 6 months experience. This is the python code receive response from my android studio. I would like to implement the same request from my spring boot so that i will be using the same python that can receive request from both android and 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)

1 Answer 1

1

For those who have similar problems as me, you can take a look into this post. Sending files using POST with HttpURLConnection It seems like a solution to my problem.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.