public static void main(String[] args) throws Exception {
try {
HttpClient client = HttpClient.newHttpClient();
HttpRequest postRequest = (HttpRequest) HttpRequest.newBuilder()
.uri(new URI("url to upload file and fetch info "))
.setHeader("Authorization", "Bearer " +tokenKey)
.setHeader("Content-Type", "multipart/form-data")
.POST(BodyPublishers.ofFile(Paths.get("\\SpringProject\\ImageProcessing\\src\\image.jpg")))
.build();
HttpResponse<String> response = client.send(postRequest, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
} catch(Exception e) {
e.printStackTrace();
}}
with the above code i am trying to upload a image file and fetch back the details related to that image. But i am getting the below error message from the response body. Please help me to sort out this problem.
{
"result": "FAILED",
"data": {
"error_code": 400004,
"error_message": "Bad Request: no files uploaded"
}
}
I suspect that you have a problem with the line:
Paths.get("\\SpringProject\\ImageProcessing\\src\\image.jpg")The problem is that if your parameter to methodPaths.getis a valid but non-existent path it will not throw an exception. I.e. pathC:\\testis valid regardless of whether this path actually exists or not and pathC\#/test\&/is invalid due to syntactic error. In your case, you provide a relative path. I suggest that you try an absolute path and actually check that it exists before passing it as your parameter. Also if you are interested I may suggest to try and use a simpler 3d party HTTP client. Here how your code may look like:Note that classes
HttpClientandFileUtilsin this code come from Open Source MgntUtils library written and maintained by me. Here is HttpClint Javadoc. The library can be obtained from the Maven Central repository or as a jar file from Github (including Javadoc and source code)