I need to catch an output of a post call to a rest service that uploads a file from Java code . The only information I have about this service is a curl command:
curl -u "username:token" \
-X POST "https://host.name.to/upload/upload" \
-F "file=@/path/to/app/fileToUpload"
So far, apart from successfully executing the curl-command, I've also successfully made the rest call through Postman
I have tried to translate the call to OkHttp as well as tried to just run the call through Java's Process api but without luck.
When I tried to let OkHttp call the service I get error 422 (even when just copy and pasting the code snippet straight from Postman)
When I try to execute curl though Process(), curl exits with code 1
Trying to call rest service using okHttp:
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", fileLocationAsString)
.build();
Request requestWithHeader = new Request.Builder()
.header("Authorization", Credentials.basic(userName, accessKey))
.header("Content-Type","multipart/form-data ")
.header("cache-control", "no-cache")
.header("Content-Disposition", "form-data; name=\"file\"; filename=" + fileLocationAsString)
.url("https://host.name.to/upload/upload")
.post(requestBody)
.build();
try {
Response response = client.newCall(requestWithHeader).execute();
uploadAppFileResponse = (JSONObject) parser.parse(response.body().string());
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
Trying to execute curl through Process:
String command = "/usr/bin/curl -u " + userName + ":" + accessKey + " -X POST \"https://host.name.to/upload\" -F file=@" + fileLocationAsString;
try {
Process process = Runtime.getRuntime().exec(command);
process.waitFor();
int exitValue = process.exitValue();
System.out.println(exitValue);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
I would like to be able to successfully execute the upload, preferably through a clean service call instead of running curl through Process() and to catch the (json) response.
Thanks in advance