【发布时间】:2016-08-03 07:22:08
【问题描述】:
我有一个远程位于 url 的文件:www.something.com/abc.txt。
我想获取这个远程文件(abc.txt) 并使用“客户端”接口将其存储在InputStream 或String 对象中。
【问题讨论】:
标签: java string httpclient inputstream
我有一个远程位于 url 的文件:www.something.com/abc.txt。
我想获取这个远程文件(abc.txt) 并使用“客户端”接口将其存储在InputStream 或String 对象中。
【问题讨论】:
标签: java string httpclient inputstream
这很简单:
HttpClient client = new HttpClient();
String url = "http://www.example.com/README.txt";
// Create a method instance.
GetMethod method = new GetMethod(url);
// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
byte[] responseBody = method.getResponseBody();
String fileContents = new String(responseBody);
Here 也是一个很好的教程,可以帮助你
希望有帮助
【讨论】:
你可以这样做:
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>
【讨论】: