0

I am using apache httpclient to upload a file to a server. I need to use basic authentication(username and password). The response in 200, however, the server logs reveal that the file in missing some data.

public static String pushdata() throws FileNotFoundException, UnsupportedEncodingException {
    File file = new File("/home/mohamed/atomtest.txt");
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user", "pass");
    provider.setCredentials(AuthScope.ANY, credentials);
    HttpClient httpclient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
    HttpEntity data = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE).addBinaryBody("file", file).build();
    HttpUriRequest request = RequestBuilder.post("link").setEntity(data).build();
    ResponseHandler<String> responseHandler = response -> {
        int status = response.getStatusLine().getStatusCode();
        System.out.println(status);
        if (status >= 200 && status < 300) {
            HttpEntity entity = response.getEntity();
            String entityString = EntityUtils.toString(entity);
            System.out.println(entityString);
            return entityString;
        } else {
            throw new ClientProtocolException("Unexpected response status: " + status);
        }
    };
    String responseBody = "pushDATA";
    try {
        responseBody = httpclient.execute(request, responseHandler);

    } catch (IOException ex) {
        System.out.println(ex.toString());
    }
    return responseBody;
}

The file is saved as UTF-16, and must be uploaded with the same encoding. kind regards.

MohamedA95
  • 36
  • 1
  • 5
  • Take care of the correct content type and encoding: https://stackoverflow.com/questions/49918204/apache-httpclient-how-to-properly-produce-multipart-requests-with-encoding – ibexit Oct 23 '18 at 09:46
  • Hello @ibexit unfortunately, this is doesn't help But the server now is giving a new exception java.io.IOException: Incomplete input stream – MohamedA95 Oct 23 '18 at 11:12
  • I removed the charset property, and now the file still is corrupted, changing the content type value does not help. – MohamedA95 Oct 23 '18 at 11:37

0 Answers0