Retrofit+Rxjava는 이미 시장에서 가장 주류 네트워크 프레임 워크입니다. 일반적인 네트워크 요청을하기 위해 사용하기가 매우 쉽습니다. Retrofit을 사용하여 파일을 업로드하고 파일을 다운로드 한 적이 있지만 Retrofit을 사용하여 다운로드하는 것은 기본적으로 진행 콜백을 지원하지는 않지만 파일을 다운로드 할 때 다운로드 진행 상황이 표시되어야하므로 들어가야합니다.
다음으로 함께 캡슐화하고 Retrofit+Rxjava를 사용하여 진행 상황이있는 파일을 다운로드합시다.
github : jsdownload
먼저 UML 다이어그램을 살펴 보겠습니다.
당신은 그것을 다루는 방법을 잘 모르겠습니다. 걱정하지 마십시오. 단계별로 가져 가겠습니다.
1. 의존성을 추가해야합니다
'io.recivityx : rxjava : 1.1.0'compile'io.recivityx : rxandroid : 1.1.0'compile 'com.squareup.retrofit2 : retrofit : 2.0-beta4'compile'com.squareup.retrofit2 : retrofit : 2.0.0-beta4'compile 'com.squareup.retrofit2 : Converter-Gson : 2.0.0-beta4'compile'com.squareup.retrofit2 : 어댑터-xjava : 2.0.0-beta4 '
버전을 사용할 때 버전 번호에주의하십시오
2. 콜백을 쓰십시오
/*** 설명 : 2017/11/30에서 JIA가 만든 진행 콜백 다운로드*. * 사람들이 할 수있는 이유는 그들이*/public interface jsdownloadListener {void onstartDownload (); void onprogress (int progress); void onfinishdownload (); void onfail (String ErrorInfo);}말할 것도없이, 다운로드 된 콜백에는 최소한 4 가지 콜백 방법이 있어야합니다. 다운로드 시작, 진행 상황 다운로드, 완료 다운로드 및 다운로드 실패.
진행률 백분율은 OnProgress 메소드에서 반환되며 실패 이유는 OnFail로 반환됩니다.
3. 응답 바디를 다시 작성하고 다운로드 백분율을 계산하십시오
/*** 설명 : 2017/11/30에 JIA가 생성 한 진행 상황이있는 요청 본문 다운로드*. * 사람들이 그렇게 할 수있는 이유는 그들이*/public class jsresponsebody를 확장 할 수 있다고 믿기 때문입니다. Private JSDownloadListener DownloadListener; // BufferedSource는 Okio 라이브러리의 입력 스트림이며 여기에서 입력 스트림으로 사용됩니다. Private BufferedSource BufferedSource; public jsresponsebody (ResponseBody ResponseBody, JSDownLoadListener downloadListener) {this.ResponseBody = responsebody; this.downloadListener = downloadListener; } @override public mediaType contentType () {return response.contentType (); } @override public long contentlength () {return response.contentLength (); } @override public bufferedSource source () {if (bufferedSource == null) {bufferedSource = okio.buffer (source (responsebody.source ())); } return bufferedSource; } 개인 소스 소스 (소스 소스) {return new ForwardingSource (소스) {Long TotalByTesRead = 0L; @override public long read (버퍼 싱크, long bytecount) ioexception {long bytesread = super.read (싱크, bytecount); // read () 읽기 수를 반환 하거나이 소스가 소진 된 경우 -1을 반환합니다. TotalByTesRead += ByTesRead! = -1? 바이트 레드 : 0; log.e ( "다운로드", "읽기 :"+ (int) (TotalBytesRead * 100 / response.contentLength ())); if (null! = downloadListener) {if (bytesRead! = -1) {downloadListener.OnProgress ((int) (TotalByTesRead * 100 / responsebody.contentLength ())); }} return bytesread; }}}; }}구조물의 네트워크 요청에 대해 ResponseBody 및 JSdownloadListener를 전달하십시오.
여기의 핵심은 소스 메소드가있는 소스 메소드입니다. 여기서 읽기 메소드를 재정의하고 읽기 메소드의 백분율을 계산하고 콜백 다운로드 listener로 전달하는 소스 소스 객체를 반환합니다.
4. 인터셉터
응답 바디 만 캡슐화하는 것만으로는 충분하지 않습니다. 핵심은 요청 된 응답 바디를 가져와야한다는 것입니다. 여기서 인터셉터를 사용합니다.
/*** 설명 : 2017/11/30에서 JIA가 생성 한 진행 상황이있는 인터셉터 다운로드*. * 사람들이 할 수있는 이유는 그들이*/public class jsdownloadinterceptor를 구현할 수 있다고 생각하기 때문입니다. public jsdownloadinterceptor (jsdownloadListener downloadListener) {this.downloadListener = downloadListener; } @override public response intercept (체인 체인) IoException {응답 응답 = chain.proceed (chain.request ()); return response.newbuilder (). body (new jsresponsebody (response.body (), downloadListener). build (); }}일반적으로 인터셉터는 요청 또는 응답 헤더 정보를 추가, 제거 또는 변환하는 데 사용됩니다.
인터셉트 메소드 인터셉트에서 방금 캡슐화 한 응답 바디를 반환합니다.
5. 네트워크 요청 서비스
/** * 설명 : * JIA가 2017/11/30에 만들었습니다. * 사람들이 할 수있는 이유는 그들이*/public interface downloadservice {@Streaming @Get Observable <sponection> download (@url string url);}를 할 수 있다고 생각하기 때문입니다.알아채다:
여기 @url은 전체 다운로드 URL을 전달합니다. @Streaming 주석 메소드를 가로 채울 필요가 없습니다
6. 최종 요청이 시작됩니다
/** 1. 설명 : 도구 클래스 2를 다운로드합니다. 3. 사람들이 그렇게 할 수있는 이유는 그들이*/public class downloadUtils {private static final String tag = "downloadUtils"를 믿기 때문입니다. 비공개 정적 최종 int default_timeout = 15; 개인 개조 개조; 개인 JSDownloadListener 리스너; 개인 문자열 baseurl; 개인 문자열 downloadUrl; public downloadUtils (String BaseUrl, JsdownloadListener Listener) {this.baseurl = baseurl; this.listener = 리스너; jsdownloadinterceptor minterceptor = 새로운 jsdownloadinterceptor (리스너); okhttpclient httpclient = new okhttpclient.builder () .addinterceptor (minterceptor) .retryonConnectionFailure (true) .ConnectTimeout (default_timeout, timeUnit.seconds) .Build (); retrofit = new retrofit.builder () .baseurl (baseurl) .Client (httpclient) .addcalladapterfactory (rxjavacalladapterfactory.create ()) .build (); } / ** * 다운로드 시작 * * @param url * @param filepath * @param 가입자 * / public void download (@nonnull string url, 최종 문자열 FilePath, 가입자 가입자) {Listener.OnStartDownLoad (); // subscribeon ()은 // joobseperon ()이라고 불리기 전에 코드의 스레드를 변경합니다. CALL (responskBody) {return responsebody.bytestream ()}) .Observeon (schedulers.computation ()) // task.doonNext (@OverRide public void call (inputStream inputStream) {writeFile, fillepath); .Observeon (AndroidSchedulers.MainThread ()) .SubScribe (가입자); } / ** * 입력 스트림을 파일에 쓰기 * * @param inputString * @param filepath * / private void writeFile (inputStream inputString, String FilePath) {file file = 새 파일 (filepath); if (file.exists ()) {file.delete (); } fileoutputStream fos = null; try {fos = new FileOutputStream (파일); 바이트 [] B = 새로운 바이트 [1024]; int len; while ((len = inputstring.read (b))! = -1) {fos.write (b, 0, len); } inputString.close (); fos.close (); } catch (filenotFoundException e) {Listener.onFail ( "FilEnotFoundException"); } catch (ioexception e) {Listener.onFail ( "ioException"); }}}물론 다운로드 콜백의 각 위치에주의를 기울여야합니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.