Search code examples
filetransfer

Hack to upload a file from Java backend to a remote server over HTTP using Rest API.


My file resides on some location on my machine say C://users//abc.txt and i want to write a java program to transfer this file using REST API over HTTP. I used MockHttpServelet Request to create the request, but somehow i am unable to transfer the file


Solution

  • Use HttpClient:

    String url = "http://localhost:8080/upload"; // Replace with your target 'REST API' url
    String filePath = "C://users//abc.txt";
    
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
        HttpPost httpPost = new HttpPost(url);
        FileEntity entity = new FileEntity(new File(filePath), ContentType.TEXT_PLAIN);
        httpPost.setEntity(entity);
    
        HttpResponse httpResponse = httpClient.execute(httpPost);
        System.out.println(httpResponse.getStatusLine().getStatusCode()); // Check HTTP code
    } finally {
        httpClient.close();
    }
    

    With Authentication:

    String url = "http://localhost:8080/upload"; // Replace with your target 'REST API' url
    String filePath = "C://users//abc.txt";
    String username = "username"; // Replace with your username
    String password = "password"; // Replace with your password
    
    RequestConfig requestConfig =
      RequestConfig.custom().
        setAuthenticationEnable(true).
        build();
    
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(
      AuthScope.ANY,
      new UsernamePasswordCredential(username, password));
    
    CloseableHttpClient httpClient =
      HttpClients.custom().
        setDefaultRequestConfig(requestConfig).
        setDefaultCredentialsProvider(credentialsProvider).
        build();
    try {
        HttpPost httpPost = new HttpPost(url);
        FileEntity entity = new FileEntity(new File(filePath), ContentType.TEXT_PLAIN);
        httpPost.setEntity(entity);
    
        HttpResponse httpResponse = httpClient.execute(httpPost);
        System.out.println(httpResponse.getStatusLine().getStatusCode()); // Check HTTP code
    } finally {
        httpClient.close();
    }