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