Java Http Client to upload file over POST

Sending files over HTTP is supposed to take place using multipart/form-data encoding. Your servlet part is fine as it already uses Apache Commons FileUpload to parse a multipart/form-data request.

Your client part, however, is apparently not fine as you're seemingly writing the file content raw to the request body. You need to ensure that your client sends a proper multipart/form-data request. How exactly to do it depends on the API you're using to send the HTTP request. If it's plain vanilla java.net.URLConnection, then you can find a concrete example somewhere near the bottom of this answer. If you're using Apache HttpComponents Client for this, then here's a concrete example, taken from their documentation:

String url = "https://example.com";
File file = new File("/example.ext");

try (CloseableHttpClient client = HttpClients.createDefault()) {
    HttpPost post = new HttpPost(url);
    HttpEntity entity = MultipartEntityBuilder.create().addPart("file", new FileBody(file)).build();
    post.setEntity(entity);

    try (CloseableHttpResponse response = client.execute(post)) {
        // ...
    }
}

Unrelated to the concrete problem, there's a bug in your server side code:

File file = new File("\files\\"+item.getName());
item.write(file);

This will potentially overwrite any previously uploaded file with the same name. I'd suggest to use File#createTempFile() for this instead.

String name = FilenameUtils.getBaseName(item.getName());
String ext = FilenameUtils.getExtension(item.getName());
File file = File.createTempFile(name + "_", "." + ext, new File("/files"));
item.write(file);

Following code can be used to upload file with HTTP Client 4.x (Above answer uses MultipartEntity which is deprecated now)

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

String uploadFile(String url, File file) throws IOException
{
    HttpPost post = new HttpPost(url);
    post.setHeader("Accept", "application/json");
    _addAuthHeader(post);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    // fileParamName should be replaced with parameter name your REST API expect.
    builder.addPart("fileParamName", new FileBody(file));
    //builder.addPart("optionalParam", new StringBody("true", ContentType.create("text/plain", Consts.ASCII)));
    post.setEntity(builder.build());
    HttpResponse response = getClient().execute(post);;
    int httpStatus = response.getStatusLine().getStatusCode();
    String responseMsg = EntityUtils.toString(response.getEntity(), "UTF-8");

    // If the returned HTTP response code is not in 200 series then
    // throw the error
    if (httpStatus < 200 || httpStatus > 300) {
        throw new IOException("HTTP " + httpStatus + " - Error during upload of file: " + responseMsg);
    }

    return responseMsg;
}

You will need recent versions of the following Apache libraries: httpclient, httpcore, httpmime.

getClient() can be replaced with HttpClients.createDefault().


Please find the sample working example for File upload functionality using HttpClient in Java.

package test;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.DefaultHttpClient;

public class fileUpload {
private static void executeRequest(HttpPost httpPost) {
    try {
        HttpClient client = new DefaultHttpClient();
        HttpResponse response = client.execute(httpPost);
        System.out.println("Response Code:  " + response.getStatusLine().getStatusCode());
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void executeMultiPartRequest(String urlString, File file) throws IOException {
    HttpPost postRequest = new HttpPost(urlString);
    postRequest = addHeader(postRequest, "Access Token");
    try {
        postRequest.setEntity(new FileEntity(file));
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    executeRequest(postRequest);
}

private static HttpPost addHeader(HttpPost httpPost, String accessToken) {
    httpPost.addHeader("Accept", "application/json;odata=verbose");
    httpPost.setHeader("Authorization", "Bearer " + accessToken);
    return httpPost;
}

public static void main(String args[]) throws IOException {
    fileUpload fileUpload = new fileUpload();
    File file = new File("C:\\users\\bgulati\\Desktop\\test.docx");
    fileUpload.executeMultiPartRequest(
            "Here Goes the URL", file);

}
}