package com.acdp.transceivr; import okhttp3.*; import okio.BufferedSink; import java.io.IOException; import java.io.InputStream; public class LoadTools { public static final MediaType MEDIA_TYPE_BINARY = MediaType.parse("application/octet-stream"); private static void download(Transfer t, ProgressListener progressListener) throws IOException { Request request = new Request.Builder() .url(t.from) .build(); OkHttpClient client = new OkHttpClient.Builder() .addNetworkInterceptor(chain -> { Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), progressListener)) .build(); }) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { t.uploadError=e.toString(); } @Override public void onResponse(Call call, Response response) throws IOException { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); try { upload(t, response.body().byteStream()); } catch (IOException e) { e.printStackTrace(); } } }); } private static void upload(Transfer t, InputStream is) throws IOException { RequestBody requestBody = new RequestBody() { @Override public MediaType contentType() { return MEDIA_TYPE_BINARY; } @Override public void writeTo(BufferedSink sink) throws IOException { is.transferTo(sink.outputStream()); } }; OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(t.to) .post(requestBody) .build(); client.newCall(request).enqueue( new Callback() { @Override public void onFailure(Call call, IOException e) { t.uploadError = e.toString(); } @Override public void onResponse(Call call, Response response) throws IOException { if (!response.isSuccessful()) { t.uploadError = response.toString(); t.uploadCode = response.code(); } t.uploadResponseBody = response.body().string(); t.uploadDone = true; } } ); } public static void startTransfer(Transfer t) throws IOException { final ProgressListener progressListener = new ProgressListener() { boolean firstUpdate = true; @Override public void update(long bytesRead, long contentLength, boolean done) { if (done) { t.downloadDone = true; } else { if (firstUpdate) { firstUpdate = false; if (contentLength == -1) { t.contentLength = -1; } else { t.contentLength = contentLength; } } t.bytesRead = bytesRead; t.currentTS = System.currentTimeMillis(); } } }; download(t, progressListener); } }