Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to alert the user using Toast that the OkHttp request returned something other than 200?

I'm using OkHttp and everything is working fine, however, I wanted to take into consideration the case where the DNS resolution is off, the server is down, slow, or simply returns something other than HTTP Status Code 200. I've tried to use Toast, but I can't since this is done on another thread (?). How do I overcome this obstacle and give the user a better experience? Here's my code:

private void getBinary(String text) throws Exception {
    OkHttpClient client = new OkHttpClient();

    String body = URLEncoder.encode(text, "utf-8");
    // Encrypt
    MCrypt mcrypt = new MCrypt();
    String encrypted = MCrypt.bytesToHex(mcrypt.encrypt(body));
    Request request = new Request.Builder()
        .url("http://mysite/my_api.php")
        .post(RequestBody.create(MediaType.parse("text/plain"), encrypted))
        .addHeader("User-Agent", System.getProperty("http.agent"))
        .build();

    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onResponse(Response response) throws IOException, RuntimeException {
            if (response.code() != 200){
                Toast.makeText(getSherlockActivity(), "Fail", Toast.LENGTH_LONG).show();
                return;
            }
            saveResponseToFile(response);
        }

        @Override
        public void onFailure(Request arg0, IOException arg1) {
            Toast.makeText(getSherlockActivity(), "Bigger fail", Toast.LENGTH_LONG).show();
        }
    });
}

Here's the crash:

FATAL EXCEPTION: OkHttp Dispatcher
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
like image 595
Naphtali Gilead Avatar asked Feb 26 '15 07:02

Naphtali Gilead


People also ask

Is OkHttp asynchronous?

OkHttp doesn't currently offer asynchronous APIs to receive a response body in parts.

What is the use of OkHttp?

OkHttp is an HTTP client from Square for Java and Android applications. It's designed to load resources faster and save bandwidth. OkHttp is widely used in open-source projects and is the backbone of libraries like Retrofit, Picasso, and many others.

Is OkHttp secure?

OkHttp includes four built-in connection specs: RESTRICTED_TLS is a secure configuration, intended to meet stricter compliance requirements. MODERN_TLS is a secure configuration that connects to modern HTTPS servers.


1 Answers

Toast must be shown on the main thread. You can use new Handler(Looper.getMainLooper()) to generate a main thread handler from any background thread, then use it to post toast work to main thread.

Code like this will work for your:

public static void backgroundThreadShortToast(final Context context,
        final String msg) {
    if (context != null && msg != null) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {

            @Override
            public void run() {
                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
            }
        });
    }
}
like image 57
Lei Guo Avatar answered Oct 02 '22 14:10

Lei Guo