123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110 |
- 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);
- }
- }
|