2016-08-03 10 views
0

私は、ファイルをURL:www.something.com/abc.txtにリモートに配置しています。Javaでクライアントインターフェイスを使用してリモートファイルを取得する方法

このリモートファイル(abc.txt)を取得して、「クライアント」インターフェイスを使用してInputStreamまたはStringオブジェクトに格納します。

+3

[Javaを使用したリモートファイルの読み取り](http://stackoverflow.com/questions/1316360/reading-a-remote-file-using-java)の可能な複製 –

答えて

1

これは非常に簡単です:

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はまた、あなたがこのようにそれを行うことができます

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> 
関連する問題