如何在java中使用Client Interface获取远程文件

时间:2016-08-03 07:22:09

标签: java string httpclient inputstream

我有一个位于网址的远程文件:www.something.com/abc.txt

我想获取此远程文件(abc.txt)并使用“客户端”界面将其存储在InputStreamString对象中。

2 个答案:

答案 0 :(得分:1)

这很简单:

$('#para1').children().get(0).tagName

Here也是一个很好的教程,可以帮助你

希望有所帮助

答案 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>