2013-08-03 2 views

답변

8

Shailen's response가 정확하고도 Stream.pipe에 조금 짧아 질 수 있습니다.

import 'dart:io'; 

main() { 
    new HttpClient().getUrl(Uri.parse('http://example.com')) 
    .then((HttpClientRequest request) => request.close()) 
    .then((HttpClientResponse response) => 
     response.pipe(new File('foo.txt').openWrite())); 
} 
2

파이썬 예 예를 들어

example.com의 내용을 요청하고 파일에 대한 응답을 작성하는 것을 포함한다. 여기

는 다트에 비슷한 일을 할 수있는 방법은 다음과 같습니다

import 'dart:io'; 

main() { 
    var url = Uri.parse('http://example.com'); 
    var httpClient = new HttpClient(); 
    httpClient.getUrl(url) 
    .then((HttpClientRequest request) { 
     return request.close(); 
    }) 
    .then((HttpClientResponse response) { 
     response.transform(new StringDecoder()).toList().then((data) { 
     var body = data.join(''); 
     print(body); 
     var file = new File('foo.txt'); 
     file.writeAsString(body).then((_) { 
      httpClient.close(); 
     }); 
     }); 
    }); 
} 
+0

그래, 그렇게 할 수는 있지만 콘텐츠가 이미지 인 경우는 어떻습니까? 고맙습니다. –

+0

Dart API는 더 짧을 수 있습니까? 새로운 HttpClient()'=>'getUrl()'=>'close()'=>'transform()'=>'새로운 StringDecoder()'=>'toList()'=>'close()'. 그리고 이것은 'then()'호출을 고려하지 않고 있습니다. – mezoni

+0

최근 버전의 Dart에서는'StringDecoder' 클래스가'UTF8.decoder'로 대체되었습니다. – lucperkins

8

나는 HTTP 패키지를 많이 사용하고 있습니다. 당신은 거대한되지 않는 파일을 다운로드하려면, 당신은 청소기 접근 방식의 HTTP 패키지를 사용할 수 있습니다 알렉상드르 쓴 무엇

import 'package:http/http.dart' as http; 

main() { 
    http.get(url).then((response) { 
    new File(path).writeAsBytes(response.bodyBytes); 
    }); 
} 

큰 파일에 대한 더 나은 수행합니다. 파일을 자주 다운로드해야하는 경우 헬퍼 함수를 ​​작성하는 것이 좋습니다.

관련 문제