简体   繁体   中英

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?

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM