我有一个位于网址的远程文件:www.something.com/abc.txt
。
我想获取此远程文件(abc.txt)
并使用“客户端”界面将其存储在InputStream
或String
对象中。
答案 0 :(得分:1)
答案 1 :(得分:0)
你可以这样做:
import org.apache.commons.io.IOUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class HttpClientUtil {
public static void main(String... args) {
CloseableHttpClient httpClient = HttpClients.custom().build();
CloseableHttpResponse response = null;
try {
HttpGet httpGet = new HttpGet("http://txt2html.sourceforge.net/sample.txt");
httpGet.setHeader("Content-Type", "text/plain");
response = httpClient.execute(httpGet);
String strValue = EntityUtils.toString(response.getEntity());
System.out.println(strValue);
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
IOUtils.closeQuietly(response);
IOUtils.closeQuietly(httpClient);
}
}
}
以下是依赖项。
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.3.1</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>