Search code examples
pythonjavapostpython-requestshttp-post

How to send an image in Java to a Python server that uses requests?


I have 2 python scripts, 1 is the server itself and the other for POST-ing and image. Server.py ->

app = Flask(__name__)

@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "POST":
        file = request.files.get('file')
        if file is None or file.filename == "":
            return jsonify({"error": "nothing inside file"})

        try:
            image_bytes = file.read()
            pillow_img = imageio.imread(image_bytes, pilmode='RGB')
            start_time = time.time()
            result = tfnet.return_predict(pillow_img)[0]
            end_time = time.time()
            result['response_time'] = end_time - start_time
            return jsonify({'Output': str(result)})
        except Exception as e:
            return jsonify({"error": str(e)})

    return "OK"

I'm trying to re-create the test.py into java, I'm able to POST to the server and get 200 response. But I'm having trouble sending and image to the server.py thats running. I'm breaking this problem into 2 parts: 1) Try POST a json for my server.py to recognize it as some JSON instead of None. 2) Try encode an image and POST it to server.py to recognize and send a response back. I'm not able to do both the steps. Test.py ->

import requests

resp = requests.post("http://xxxxxxxxxxxxxx:8080/", 
                    files={'file': open('D://Jupyter//GCP Deploy//darkflow-master//1.jpg', 'rb')})

print(resp.json())

and the respective java file that doesnt send the image but a json.

public class HttpURLConnectionExample {
public static void main(String[] args) throws IOException {
    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
        HttpPost httpPost = new HttpPost("http://xxxxxxxxxxxxxx:8080/");
        String json = "{\r\n" +
            "  \"file\": \"string value\"\r\n" +
            "}";
            
        StringEntity stringEntity = new StringEntity(json);
        httpPost.setEntity(stringEntity);
        System.out.println("Executing request " + httpPost.getRequestLine());

        // Create a custom response handler
        ResponseHandler < String > responseHandler = response -> {
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }
        };
        String responseBody = httpclient.execute(httpPost, responseHandler);
        System.out.println("----------------------------------------");
        System.out.println(responseBody);
    }
}

}

The only success I'm having from this is that the server recognizes the POST request, but doesnt go into the try block, the file in the Server.py is None.


Solution

  • file = request.files.get('file')
    

    This line in Server.py was changes to request.get_data() to get the raw data being transfered. However, the problem now is with the bytes file of image. Java POST request of bytes image is of varying length when run multiple times, Python POST request has fixed bytes of image when run multiple times.

    eg: Python POST request of image => 474525 length (fixed on every run) Java POST request of image => 474741, 474744, 474740 length (Varying on every run)