EzDevInfo.com

okio

A modern I/O API for Java Okio 1.4.0 API

How to use Retrofit and SimpleXML together in downloading and parsing an XML file from a site?

I just started working with Retrofit. I am working on a project that uses SimpleXML. Can somebody provide me an example in which one fetches an XML from a site e.g. http://www.w3schools.com/xml/simple.xml" and reads it out?


Source: (StackOverflow)

Android-Studio-1.2.RC Proguard warnings on Square's Okio library reference

WIth Android Studio: 1.2.RC

I enabled proguard in .gradle: ```

minifyEnabled=true

and added these rules to my proguard-rules.pro:

-dontwarn com.squareup.**
-dontwarn okio.**

and added these lint rules to my .gradle file:

warningsAsErrors false
abortOnError false
disable 'InvalidPackage'

```

But I still get these warning when I try to run the app in debug mode:

```
Warning: okio.DeflaterSink: can't find referenced class org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement
Warning: okio.Okio: can't find referenced class java.nio.file.Files
Warning: okio.Okio: can't find referenced class java.nio.file.Files
Warning: okio.Okio: can't find referenced class java.nio.file.Files
Warning: okio.Okio: can't find referenced class java.nio.file.Path
Warning: okio.Okio: can't find referenced class java.nio.file.OpenOption
Warning: okio.Okio: can't find referenced class java.nio.file.Path
Warning: okio.Okio: can't find referenced class java.nio.file.OpenOption
Warning: okio.Okio: can't find referenced class org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement
Warning: okio.Okio: can't find referenced class java.nio.file.Path
Warning: okio.Okio: can't find referenced class java.nio.file.OpenOption
Warning: okio.Okio: can't find referenced class java.nio.file.Path
Warning: okio.Okio: can't find referenced class java.nio.file.OpenOption
Warning: okio.Okio: can't find referenced class org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement
Warning: there were 14 unresolved references to classes or interfaces.
         You may need to add missing library jars or update their versions.
         If your code works fine without the missing classes, you can suppress
         the warnings with '-dontwarn' options.
         (http://proguard.sourceforge.net/manual/troubleshooting.html#unresolvedclass)
:app:proguardDebug FAILED

```

It's so weird since I also added these rules/options to all my library modules that depend on OkHttp/Picasso, I don't know where went wrong, perhaps this is a Android Studio bug ? Does anyone have any clues to this problem ?

I have opened an issue on github.


Source: (StackOverflow)

Advertisements

Handling Authentication in Okhttp

I'm using OkHttp 2.3 with basic authentication requests, according to OKHttp docs, it automatically retries unauthenticated requests, but whenever I provide invalid credentials, the request takes too much time and I get this exception in the end:

java.net.ProtocolException: Too many follow-up requests: 21

How can I prevent OkHttp from automatically retrying unauthenticated requests, and return 401 Unauthorized instead?


Source: (StackOverflow)

Okio EOFException on polling rest call

I'm trying to use rxjava with retrofit to implement a polling rest call. It looks like everything is correct but then there is no body response. I can assure with postman and curl that the server response is correct. The error is java.io.EOFException. Any idea?

ERROR LOG

09-22 13:52:30.296  12746-12884/com.. D/Retrofit﹕ ---> HTTP POST http://192.168.1.11:9621/checkredeem
09-22 13:52:30.296  12746-12884/com.. D/Retrofit﹕ Content-Type: application/json; charset=UTF-8
09-22 13:52:30.296  12746-12884/com.. D/Retrofit﹕ Content-Length: 52
09-22 13:52:30.296  12746-12884/com.. D/Retrofit﹕ {"ordercode":"","tag":"NO_TAG_AVAILABLE","status":0}
09-22 13:52:30.306  12746-12884/com.. D/Retrofit﹕ ---> END HTTP (52-byte body)
09-22 13:52:30.396  12746-12884/com.. D/Retrofit﹕ <--- HTTP 200 http://192.168.1.11:9621/checkredeem (88ms)
09-22 13:52:30.396  12746-12884/com.. D/Retrofit﹕ Content-Type: application/json
09-22 13:52:30.406  12746-12884/com.. D/Retrofit﹕ Vary: Accept-Encoding
09-22 13:52:30.406  12746-12884/com.. D/Retrofit﹕ X-Powered-By: wolley-service-fwk
09-22 13:52:30.406  12746-12884/com.. D/Retrofit﹕ Date: Tue, 22 Sep 2015 11:52:30 GMT
09-22 13:52:30.406  12746-12884/com.. D/Retrofit﹕ OkHttp-Selected-Protocol: http/1.1
09-22 13:52:30.416  12746-12884/com.. D/Retrofit﹕ OkHttp-Sent-Millis: 1442922750345
09-22 13:52:30.426  12746-12884/com.. D/Retrofit﹕ OkHttp-Received-Millis: 1442922750390
09-22 13:52:30.426  12746-12884/com.. D/Retrofit﹕ ---- ERROR http://192.168.1.11:9621/checkredeem
09-22 13:52:30.466  12746-12884/com.. D/Retrofit﹕ java.io.EOFException: source exhausted prematurely
            at okio.InflaterSource.read(InflaterSource.java:82)
            at okio.GzipSource.read(GzipSource.java:80)
            at okio.RealBufferedSource$1.read(RealBufferedSource.java:371)
            at java.io.InputStream.read(InputStream.java:163)
            at retrofit.Utils.streamToBytes(Utils.java:43)
            at retrofit.Utils.readBodyToBytesIfNecessary(Utils.java:81)
            at retrofit.RestAdapter.logAndReplaceResponse(RestAdapter.java:483)
            at retrofit.RestAdapter.access$500(RestAdapter.java:107)
            at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:338)
            at retrofit.RestAdapter$RestHandler.invoke(RestAdapter.java:240)
            at $Proxy0.syncCall(Native Method)
            at com...view.MainActivity$6.call(MainActivity.java:72)
            at com...view.MainActivity$6.call(MainActivity.java:69)
            at rx.internal.operators.OperatorMap$1.onNext(OperatorMap.java:55)
            at rx.internal.operators.OnSubscribeTimerPeriodically$1.call(OnSubscribeTimerPeriodically.java:51)
            at rx.Scheduler$Worker$1.call(Scheduler.java:120)
            at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
            at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:390)
            at java.util.concurrent.FutureTask.run(FutureTask.java:234)
            at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:153)
            at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:267)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
            at java.lang.Thread.run(Thread.java:856)
09-22 13:52:30.466  12746-12884/com.. D/Retrofit﹕ ---- END ERROR
09-22 13:52:30.476  12746-12884/com.. E/App﹕ Polling call failed

Gradle

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.2.1'
    compile 'com.android.support:design:22.2.1'
    compile 'com.squareup.retrofit:retrofit:1.9.0'
    compile 'com.squareup.okhttp:okhttp:2.5.0'
    compile 'com.squareup.okio:okio:1.6.0'
    compile 'com.google.code.gson:gson:2.3.1'
    compile 'io.reactivex:rxjava:1.0.14'
    compile 'io.reactivex:rxandroid:1.0.1'
    compile 'com.jakewharton:butterknife:7.0.1'
}

MainActivity

final ApiCall service = RestServiceFactory.createService(ApiCall.class, Constant.SERVERURL);
mSubscription = Observable.interval(Constant.POLLINGPERIOD, TimeUnit.SECONDS)
        .map(new Func1<Long, Redeem>() {
            public Redeem call(Long tick) {
                return service.syncCall(new OutgoingDataFormat(Constant.INFO, "", 0));
            }
        }).doOnError(new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                Log.e("App", "Polling call failed");
            }
        }).retry()
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Action1<Redeem>() {
                       @Override
                       public void call(Redeem redeem) {
                           Log.d("App","Done: "+redeem);
                           startHandlingRedeemACtivity(redeem);
                       }
                   }, new Action1<Throwable>() {
                       @Override
                       public void call(Throwable throwable) {
                           //should never be performed due to doOnError function
                           throwable.printStackTrace();
                       }
                   }
        );

RestServiceFactory

public static <T> T createService (Class<T> serviceClass, String endpoint) {
        RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint(endpoint)
                .setClient(new OkClient(new OkHttpClient()))
                //.setExecutors(executor, executor)
                .build();
        restAdapter.setLogLevel(RestAdapter.LogLevel.FULL);
        return restAdapter.create(serviceClass);
    }

ApiCall

public interface ApiCall {
    @POST(Constant.PHASE1_SYNC)
    Redeem syncCall(@Body OutgoingDataFormat data);
}

Source: (StackOverflow)

Download progress with RxJava, OkHttp and Okio in Android

In our app I download an image file with this code. I need to show download progress(downloaded bytes in percentage) on UI. How I can get download progress in this code? I searched for solution, but still can't manage to do it on my own.

Observable<String> downloadObservable = Observable.create(
                    sub -> {
                        Request request = new Request.Builder()
                                .url(media.getMediaUrl())
                                .build();
                        Response response = null;
                        try {
                            response = http_client.newCall(request).execute();
                            if (response.isSuccessful()) {
                                Log.d(TAG, "response.isSuccessful()");
                                String mimeType = MimeTypeMap.getFileExtensionFromUrl(media.getMediaUrl());
                                File file = new File(helper.getTmpFolder() + "/" + helper.generateUniqueName() + "test." + mimeType);
                                BufferedSink sink = Okio.buffer(Okio.sink(file));
                                sink.writeAll(response.body().source());
                                sink.close();
                                sub.onNext(response.toString());
                                sub.onCompleted();
                            } else {
                                sub.onError(new IOException());
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
            );

            Subscriber<String> mySubscriber = new Subscriber<String>() {
                @Override
                public void onNext(String responseString) {
                    Log.d(TAG, "works: " + responseString);
                }
            };
            downloadObservable
                    .subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(mySubscriber);

Source: (StackOverflow)

why can I only read 2048 bytes at a time from an okhttp.Response InputStream?

I am downloading a file using an OkHttp GET request:

import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
...
OkHttpClient okClient = new OkHttpClient();
Request request = Request.Builder().url(url).get();
Response response = okClient.newCall(request).execute();

I read from the response body and decorating it with a BufferedInputStream, with a buffer size of 4096:

BufferedInputStream in = new BufferedInputStream(response.body().byteStream(), 4096);

However, when I try to read from the buffer, the first read returns 1179 bytes. After that, I am only able to read 2048 bytes at a time:

byte[] buffer = new byte[4096];
while (true) {
    int bytesRead = in.read(buffer); //bytesRead is always 2048, except the first read
    if (bytesRead == -1) break;
}

Several related questions:

  1. What could be causing the first read to return 1179 bytes? Some sort of file header?
  2. Why are reads from the InputStream being paged to a size of 2048 bytes, instead of the value specified by the BufferedInputStream wrapper?
  3. Is there a way to configure the OkHttpClient to read more than 2048 bytes from the buffer?

Source: (StackOverflow)

Okhttp NoClassDefFoundError

I am using OkHttp 2.0.0 jar in my android application on eclipse. As OkHttp is now dependent on Okio library, I also added Okio 1.0.0 jar in my project.The project compiles fine with no compilation errors but when I run on my android device, it gives me this NoClassDefFoundError all relating to the OkHttp library classes.

I have placed all the jars in my libs folder of the project and added them to my build path and also tried checking them in the Export and Order Tab, but still it is not working.

I wanted to know since okhttp is dependent on okio, will just adding both jars would work fine or would I have to do anything different.

I have also tried the volley jar and it works all fine without any trouble.Anyone could help me out here, the problem is around for now 3 to 4 days.

Update I also tried the android studio and added the okhttp library in the build dependency but still not working.


Source: (StackOverflow)

Fail to run app using OkHttp on 'Android L' emulator

Our app uses latest version of OkHttp (2.0.0) + Okio (1.0.0) + Picasso (2.3.2) and I wanted to try it out on the new "Android L" emulator (Intel) and it gets installed but when loading the app i get this:

06-27 09:47:16.214: E/AndroidRuntime(2815): FATAL EXCEPTION: main
06-27 09:47:16.214: E/AndroidRuntime(2815): java.lang.NoSuchMethodError: No static method source(Ljava/io/File;)Lokio/Source; in class Lokio/Okio; or its super classes (declaration of 'okio.Okio' appears in /system/framework/okhttp.jar)
06-27 09:47:16.214: E/AndroidRuntime(2815):     at   com.squareup.okhttp.internal.DiskLruCache.readJournal(DiskLruCache.java:243)
06-27 09:47:16.214: E/AndroidRuntime(2815):     at com.squareup.okhttp.internal.DiskLruCache.open(DiskLruCache.java:224)
06-27 09:47:16.214: E/AndroidRuntime(2815):     at com.squareup.okhttp.Cache.<init>(Cache.java:146)
06-27 09:47:16.214: E/AndroidRuntime(2815):     at com.squareup.picasso.OkHttpDownloader.<init>(OkHttpDownloader.java:74)
06-27 09:47:16.214: E/AndroidRuntime(2815):     at com.squareup.picasso.OkHttpDownloader.<init>(OkHttpDownloader.java:51)
06-27 09:47:16.214: E/AndroidRuntime(2815):     at com.squareup.picasso.OkHttpDownloader.<init>(OkHttpDownloader.java:41)
06-27 09:47:16.214: E/AndroidRuntime(2815):     at com.squareup.picasso.Utils$OkHttpLoaderCreator.create(Utils.java:407)
06-27 09:47:16.214: E/AndroidRuntime(2815):     at com.squareup.picasso.Utils.createDefaultDownloader(Utils.java:255)
06-27 09:47:16.214: E/AndroidRuntime(2815):     at com.squareup.picasso.Picasso$Builder.build(Picasso.java:596)

It comes from the creation of the Picasso object with Picasso.with(Context). Note that the same code, without any change works great on the previous emulator 4.4.2 (Intel).

I don't understand where this (declaration of 'okio.Okio' appears in /system/framework/okhttp.jar) is coming from.

UPDATE

I'm using Eclipse Luna with the latest Android SDK tools..I also tried to select the OkHttp jars in the Order/Export and the error persists..

I used the DDMS File Explorer and i found a okhttp.jar (309 bytes) in the path /system/framework/okhttp.jar of the emulator. Maybe this is causing the problem, but why wouldn't it lookup my own okhttp.jar provided in the APK?

I temporarily uploaded the referred 'okhttp.jar' file to this link: http://www.filedropper.com/okhttp


Source: (StackOverflow)

Streaming okhttp response body

I'm implementing a Server-Sent Events library using OkHttp. Server Sent Events works by keeping an open HTTP connection to the server on which 'events' can be streamed back to the client. The connection will only close on errors, or if the client explicitly disconnects.

What's the best way to achieve this streaming behaviour using OkHttp? I've attempted to do something like:

        response.body().source().readAll(new Sink() {
            @Override
            public void write(Buffer source, long byteCount) throws IOException {
                Log.d(TAG, "write(): byteCount = "+byteCount);
            }

            @Override
            public void flush() throws IOException {
                Log.d(TAG, "flush()");
            }

            @Override
            public Timeout timeout() {
                return Timeout.NONE;
            }

            @Override
            public void close() throws IOException {
                Log.d(TAG, "close()");
            }
        });

With this approach I will eventually see the log message in write(), but it can sometimes take quite a while (minutes). That makes me think there might be some buffering going on under the hood and I don't get my data until the buffer is flushed.

I've used curl to verify the server is behaving correctly. The data is being sent on time, I'm just not getting my callback when it arrives.

My experience with OkHttp and Okio is very limited, so it's very possible I've messed something up, or have forgotten to set some option. Any help is greatly appreciated! :)


Source: (StackOverflow)

Downloading files using OkHttp, Okio and RxJava

I'm trying to download files using OkHttp and writing to disk with Okio. Also I've created an rx observable for this process. It is working, however it is noticeably slower than what I had previously used (Koush's Ion library).

Here's how I create the observable:

public Observable<FilesWrapper> download(List<Thing> things) {
    return Observable.from(things)
        .map(thing -> {
            File file = new File(getExternalCacheDir() + File.separator + thing.getName());

            if (!file.exists()) {
                Request request = new Request.Builder().url(thing.getUrl()).build();
                Response response;
                try {
                    response = client.newCall(request).execute();
                    if (!response.isSuccessful()) new IOException();
                    else {
                        BufferedSink sink = Okio.buffer(Okio.sink(file));
                        sink.writeAll(response.body().source());
                        sink.close();
                    }
                } catch (IOException e) {
                    new IOException();
                }
            }

            return file;
        })
        .toList()
        .map(files -> new FilesWrapper(files);
}

Does anyone know what could be causing the slow speed, or if I am using the operators incorrectly?


Source: (StackOverflow)

java.lang.VerifyError when using OkHttp

I use this code in my android studio project:

HttpUrl url = new HttpUrl.Builder().scheme("http").host("www.somesite.com")
                                    .addPathSegment("kontakt")
                                    .addQueryParameter("yit_contact[imie]", name)
                                    .addQueryParameter("yit_contact[email]", email)
                                    .addQueryParameter("yit_contact[telefon]", telephone)
                                    .addQueryParameter("yit_contact[wiadomosc]", message)
                                    .addQueryParameter("yit_bot", "")
                                    .addQueryParameter("_wp_http_referer", "/kontakt/").build();
Request request = new Request.Builder().url(url).build();
Response response = new OkHttpClient().newCall(request).execute();

and I get this error when I try to get Response object:

java.lang.RuntimeException: An error occured while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:299)
        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
        at java.util.concurrent.FutureTask.run(FutureTask.java:239)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
        at java.lang.Thread.run(Thread.java:856)
 Caused by: java.lang.VerifyError: com/squareup/okhttp/internal/http/HttpConnection$AbstractSource
        at com.squareup.okhttp.internal.http.HttpConnection.newFixedLengthSource(HttpConnection.java:246)
        at com.squareup.okhttp.internal.http.HttpTransport.getTransferStream(HttpTransport.java:125)
        at com.squareup.okhttp.internal.http.HttpTransport.openResponseBody(HttpTransport.java:110)
        at com.squareup.okhttp.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:926)
        at com.squareup.okhttp.internal.http.HttpEngine.access$300(HttpEngine.java:95)
        at com.squareup.okhttp.internal.http.HttpEngine$NetworkInterceptorChain.proceed(HttpEngine.java:902)
        at com.squareup.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:760)
        at com.squareup.okhttp.Call.getResponse(Call.java:274)
        at com.squareup.okhttp.Call$ApplicationInterceptorChain.proceed(Call.java:230)
        at com.squareup.okhttp.Call.getResponseWithInterceptorChain(Call.java:201)
        at com.squareup.okhttp.Call.execute(Call.java:81)
        at com.example.tomek.myapplication.KontaktActivity$SendEmail.doInBackground(KontaktActivity.java:135)
        at com.example.tomek.myapplication.KontaktActivity$SendEmail.doInBackground(KontaktActivity.java:87)
        at android.os.AsyncTask$2.call(AsyncTask.java:287)
        at java.util.concurrent.FutureTask.run(FutureTask.java:234)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
            at java.lang.Thread.run(Thread.java:856)

I have added jar files to project:

compile files('libs/okhttp-2.4.0.jar')
compile files('libs/okio-1.0.0.jar')

Help.


Source: (StackOverflow)

Parameters not being sent using OkHTTP for Android Studio

So, I'm using Android Studio 1.2.1.1, oKhttp 2.5.0, okio 1.6.0, I have set dependencies correctly (I believe), and I have looked everywhere so i must be doing something very simple incorrectly as no one else seems to have an issue with this.

I have a Java class called OkHttpPostHandler with the following code

import android.os.AsyncTask;

import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import java.io.IOException;

public class OkHttpPostHandler extends AsyncTask<String, Void, String> {

OkHttpClient client = new OkHttpClient();
String varUser, varPass;

public OkHttpPostHandler(String varUser, String varPass) {
    this.varUser = varUser;
    this.varPass = varPass;
}

@Override
protected String doInBackground(String... params){
    RequestBody formBody = new FormEncodingBuilder()
            .add("u", varUser)
            .add("p", varPass)
            .build();
    Request request = new Request.Builder()
            .url(params[0]).post(formBody)
            .build();
    try {
        android.util.Log.w("Test", formBody.toString());
                Response response = client.newCall(request).execute();
        if (!response.isSuccessful())
            throw new IOException("unexpected code " + response.toString());
        return response.body().string();
    } catch (Exception e) {
    }
    return null;
}

}

And I have a button which reads two EditText views to gain Username and Password, which then fires off the http call:

@Override
public void onClick(View bnLoginSubmit) {
    EditText loginUsernameFont = (EditText) findViewById(R.id.evUsername);
    EditText loginPasswordFont = (EditText) findViewById(R.id.evPassword);

    String varUsername = loginUsernameFont.getEditableText().toString();
    String varPassword = loginPasswordFont.getEditableText().toString();
    String varPasswordHash = BCrypt.hashpw(varPassword, BCrypt.gensalt());

    if (varUsername.isEmpty() || varPassword.isEmpty() || varUsername.contentEquals("") || varPassword.contentEquals("")) {
        Toast.makeText(getApplicationContext(), "Username and/or Password Cannot be Empty",
                Toast.LENGTH_LONG).show();
    } else {
        // sendPostRequest(varUsername, varPasswordHash);
        boolean varPassCheck = BCrypt.checkpw("Password", varPasswordHash);
        OkHttpPostHandler handler = new OkHttpPostHandler("Username_String","Password_String");
        String result = null;
        try {
            result = handler.execute("http://www.example.com").get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        Toast.makeText(getApplicationContext(), "PHP Response = " + result,
                Toast.LENGTH_LONG).show();
    }
}

I assumed the issue was with my bcrypt hashing (so I am using manually entered strings for testing), but that seems to work beautifully. It's just that my parameters are not being passed through. If I enter the parameters manually into the URL it returns correctly, but I would prefer to be able to build on this class so it can be dynamic for future calls.

Can anyone see what I'm doing wrong? It has to be something simple. Any help would be appreciated as I'm struggling to identify the issue.


Source: (StackOverflow)

Problems decoding an image file copied using Okio and ContentResolver.openInputStream()

I have the following setup: a gallery image gets selected using Intent.ACTION_GET_CONTENT intent and then in onActivityResult() I get an Intent with an Uri. Next I try to do the following:

Source source = Okio.source(getContentResolver().openInputStream(intent.getData()));
BufferedSink sink = Okio.buffer(Okio.sink(new File(outPath)));
long bytesWritten = sink.writeAll(source);

Here outPath is a valid path to existing 0-length file created in advance.

The copy operation completes without an error, bytesWritten return an actual bytes, which are same as the source file's size.

But when I do this afterwards:

BitmapFactory.decodeFile(outFile);

It returns null and produces a skia: decoder returned false log message. Which usually means that file's format is wrong.

Why is that? I also tried to do the same thing without using Okio (just writing a lot of ugly code which copies InputStream to OutputStream) and results were the same. Any hints?

Note, that the following works, but it has the downside that I have to additionally decode Bitmap. While I'd rather just copy InputStream to a file.

Bitmap b = BitmapFactory.decodeStream(getContentResolver().openInputStream(intent.getData()));
outStream = new FileOutputStream(outFile);
b.compress(Bitmap.CompressFormat.JPEG, 92, outStream);

Source: (StackOverflow)

Opening the connection using okhttp

I'm trying to Open the connection using okhttp.

something like,

urlConnection = client.open(url);

does not work with the new ok-http.jar file.

It was working with 1.5.x of okhttp version

Any suggestions?

Thanks


Source: (StackOverflow)

Using Okio to transfer large byte [] but without exact size over bluetooth and read it in one shot

I am trying to use Okio to read out the byte array I sent over bluetooth. It is very important to read it all in one chunk because the byte array is actually a protobuffer which I than transofrm back into an object. Is there any way to do it with Okio? From what I have understood it handels the buffer size automatically. However, till now I haven't succeeded in using it correctly.


Source: (StackOverflow)