I'm trying to send the equivalent of the curl '-F' option to a designated URL.
This is what the command looks like using Curl:
curl -F"optionName=cool" -F"file=@myFile" http://myurl.com
I believe I am correct in using the HttpPost class in the Apache httpcomponents library.
I supply a name=value type of parameter. The optionName is simply a string and the 'file' is a file I have stored locally on my drive (hence the @myFile to indicate its a local file).
If I print the response I get an HTTP 500 error... I am not sure what is causing the issue here because the server responds as it should when using the Curl command mentioned above. Is there some simple mistake I am making when looking at the code below?
HttpPost post = new HttpPost(postUrl);
HttpClient httpClient = HttpClientBuilder.create().build();
List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
nvps.add(new BasicNameValuePair(optionName, "cool"));
nvps.add(new BasicNameValuePair(file, "@myfile"));
try {
post.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
HttpResponse response = httpClient.execute(post);
// do something with response
} catch (Exception e) {
e.printStackTrace();
}
Try to use a
MultipartEntity
instead of anUrlEncodedFormentity
, to handle both parameters and file upload:Edit
MultipartEntity
is deprecated andFileBody
constructor takes aFile
, not aString
, so:Thanks @CODEBLACK .