Todor Kolev
Todor Kolev

Reputation: 1482

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?

Upvotes: 4

Views: 3558

Answers (3)

ttulka
ttulka

Reputation: 10882

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

Upvotes: 1

ok2c
ok2c

Reputation: 27528

HttpClient is, surprisingly enough, is a client side HTTP transport library. It does not support any other transport protocols. Not even local file system. What you probably want is Apache Commons VFS or something similar.

Upvotes: 4

erosb
erosb

Reputation: 3141

what about using the built-in java.net.URL class? That handles both http and file protocols.

Upvotes: -1

Related Questions