简体   繁体   English

来自本地文件系统的Ap​​ache httpclient GET文件?

[英]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. 当我创建一个HttpGet实例时, HttpGet

Does anybody know how this can be done? 有谁知道如何做到这一点?

HttpClient is, surprisingly enough, is a client side HTTP transport library. 令人惊讶的是,HttpClient是一个客户端HTTP传输库。 It does not support any other transport protocols. 它不支持任何其他传输协议。 Not even local file system. 甚至不是本地文件系统。 What you probably want is Apache Commons VFS or something similar. 你可能想要的是Apache Commons VFS或类似的东西。

HttpClient is really only for HTTP, but you can achieve the same with plain Java: HttpClient实际上只适用于HTTP,但您可以使用普通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? 那么使用内置的java.net.URL类呢? That handles both http and file protocols. 它处理http和文件协议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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