GET 要求を介してファイルをダウンロードする目的で、HTTP 通信オブジェクトを開発しました。
これは、テキスト ファイルをダウンロードするときに問題なく機能します。ただし、zip、gz、tar.gz などの圧縮ファイルをダウンロードすると、ファイルがダウンロードされたように見えますが、ファイルは有効ではありません。
zip の場合、ファイルの開始前にポインターを移動しようとしたというメッセージが表示されます。.tar.gz の場合、メッセージは file.tar のデータ エラーです。ファイルが壊れています。
すべての場合において、私が使用するダウンロード リンクでは、URL から完全かつ正確にダウンロードできます。ただし、Java コード ベースのダウンロードはファイルをダウンさせますが、有効ではありません。
コードは次のとおりです。
public class HTTPCommunicationGet {
private URIBuilder sendData;
private URI target;
private HttpGet getConnection;
public HTTPCommunicationGet(String url, TreeMap<String, String> components) {
super(url, components);
}
public HTTPCommunicationGet(String url, String queryString) {
super(url, queryString);
}
protected void defineSendData() throws URISyntaxException, IOException {
this.sendData = new URIBuilder(new URI(this.getUrl()));
if (this.getComponents() != null && this.getComponents().size() > 0) {
for (Map.Entry<String, String> component : this.getComponents().entrySet()) {
this.sendData.setParameter(component.getKey(), component.getValue());
}
}
}
protected void retrieveRemoteData() throws IOException, MalformedURLException, URISyntaxException, DataMapHTTPGetException {
this.target = this.sendData.build();
this.getConnection = new HttpGet(target);
HttpResponse response = client.execute(this.getConnection);
if (response.getStatusLine().toString().toUpperCase().contains("200 OK")) {
this.setResponse(response.getStatusLine().toString(), "Data Retrieved");
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
this.remoteData.append(line);
}
} else {
String message = String.format("%s: Provider connection exception; response returned was not 200 OK", this.target.toASCIIString());
this.setResponse(response.getStatusLine().toString(), message);
DataMapHTTPGetException ex = new DataMapHTTPGetException(target.toString(), message);
throw ex;
}
}
public void downloadFiles(String localFile) throws DataMapConnectionException, FileNotFoundException, IOException, URISyntaxException {
// check that we have remoteData set
this.defineSendData();
this.retrieveRemoteData(); // everything is bubbled up to the controller class that is calling this.
File localMetaFile = new File(localFile);
switch (this.archiveMetaFile(localMetaFile)) {
case -1:
IOException ex = new IOException(String.format("The file %s could not be moved", localFile));
throw ex;
//break;
case 0:
infoLog.info(String.format("%s: this file did not already exist", localFile));
break;
case 1:
infoLog.info(String.format("%s: this file was found and successfully archived to the processed directory", localFile));
break;
}
BufferedWriter fileWriter = new BufferedWriter(new FileWriter(localFile));
fileWriter.write(this.remoteData.toString());
fileWriter.close();
}
}
ご覧のとおり、これはオブジェクトが初期化された後に downloadFiles を介して呼び出されます。archiveMetaFile メソッドなど、この例では必要のないコードを切り取っています。
これが圧縮ファイルで機能しない理由についてのポインタは大歓迎です。
乾杯ネイサン