Reputation: 7839
I have a file located remotely at url : www.something.com/abc.txt
.
I want to fetch this remote file(abc.txt)
and store it in InputStream
or String
object using 'Client' Interface.
Upvotes: 0
Views: 265
Reputation: 912
You can do it this way:
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);
}
}
}
Here are the dependencies.
<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>
Upvotes: 0
Reputation: 17839
This is very simple:
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 is also a nice tutorial that can help you out
Hope that helps
Upvotes: 1