HttpPost arguments posted to server returns HTTP 500 error

955 views Asked by At

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();
    } 
1

There are 1 answers

0
ssssteffff On BEST ANSWER

Try to use a MultipartEntity instead of an UrlEncodedFormentity, to handle both parameters and file upload:

MultipartEntity entity = new MultipartEntity();
entity.addPart("optionName", "cool");
entity.addPart("file", new FileBody("/path/to/your/file"));
....

post.setEntity(entity);

Edit

MultipartEntity is deprecated and FileBody constructor takes a File, not a String, so:

MultipartEntityBuilder entity = MultipartEntityBuilder.create();
entity.addTextBody("optionName", "cool");
entity.addPart("file", new FileBody(new File("/path/to/your/file")));
....
post.setEntity(entity.build());

Thanks @CODEBLACK .