Apache httpclient GET file from local filesystem

Apache httpclient GET file from local filesystem



  I somehow always thought that this should be possible:

val client = HttpClients.createDefault()
val httpGet = new HttpGet("file:///Users/user01/testfile")
client.execute(httpGet)
which throws:

client: org.apache.http.impl.client.CloseableHttpClient = org.apache.http.impl.client.InternalHttpClient@4ba3987b
httpGet: org.apache.http.client.methods.HttpGet = GET file:///Users/user01/testfile HTTP/1.1
org.apache.http.client.ClientProtocolException: URI does not specify a valid host name: file:///Users/user01/testfile
    at org.apache.http.impl.client.CloseableHttpClient.determineTarget(test_ws.sc0.tmp:90)
    at org.apache.http.impl.client.CloseableHttpClient.execute(test_ws.sc0.tmp:78)
    at org.apache.http.impl.client.CloseableHttpClient.execute(test_ws.sc0.tmp:103)
    at #worksheet#.#worksheet#(test_ws.sc0.tmp:6)
which kind of makes sense as I am creating an HttpGet instance.

Does anybody know how this can be done?



Solution


HttpClient is really only for HTTP, but you can achieve the same with plain Java:

try (BufferedInputStream in = new BufferedInputStream(new URL("file:///tmp/test.in").openStream());
     FileOutputStream fileOutputStream = new FileOutputStream(new File("/tmp/test.out"))){
    byte dataBuffer[] = new byte[1024];
    int bytesRead;
    while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
        fileOutputStream.write(dataBuffer, 0, bytesRead);
    }
} catch(IOException e){
    e.printStackTrace();
}



Still waiting you help, put your proposition in a comment !

No comments

Powered by Blogger.