1

I'm trying to replicate, using Java, a very simple Python function that calls a remote service. I don't have the service documentation. Here's the Python code:

def sendImage(addr, image_path):
    image = open(image_path, 'rb').read()
    files = { 'image': ('Image.jpg', image, 'image/jpg') }
    response = requests.post(addr, files = files)
    print(response.text)

But I can't seem to get this to work. Here's my Java code so far:

try {

    URL url = new URL(request);
    HttpURLConnection connection = (HttpURLConnection) url
            .openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "image/jpeg");
    connection.setConnectTimeout(Constants.TIMEOUT);
    connection.setReadTimeout(Constants.TIMEOUT);
    try (OutputStream out = connection.getOutputStream()) {
        IOUtils.copy(image, out);
    }
    try (InputStream in = connection.getInputStream()) {
        Map<String, String> originalResponse = mapper.readValue(in, TypeFactory.defaultInstance().constructMapType(HashMap.class, String.class, String.class));
    }

}
catch (Exception e) {
    e.printStackTrace();
}

I'm calling both functions with the same addr and using the same image, but when I run my Java code, the app hangs in this line for a few seconds

try (InputStream in = connection.getInputStream()) {

and then I get a "400: Bad Request" response.

Why is this not working, and how can I make it work? Thanks in advance

David Antelo
  • 503
  • 6
  • 19

1 Answers1

1

response = requests.post(addr, files = files) is file upload with multipart encoding (see api reference) and in your java code you just write file content as body of request.

If you want to write code to properly handle multipart request, then check out this RFC, what you must include in request body.

My suggestion would be to use some http client. Here is example of upload with okhttp.

Bartek Jablonski
  • 2,649
  • 24
  • 32