Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.


Max Wei
Max Wei
6,399 Points

okhttp asynchronous post always executing onFailure

Hi! I'm trying to perform an asynchronous post with okhttp. I'm trying to send a string specified by postBody (an email and password) and i'm expecting to get a string in response (an authentication token). When the code is executed, the onFailure method is always executed after a slight delay. Can anyone spot any blatant mistakes?

String url = "https://hoverapp.herokuapp.com/authenticate"; String email = "d1@example.com"; String password = "password";

            = MediaType.parse("text/plain; charset=utf-8");

    OkHttpClient client = new OkHttpClient();

    String postBody = "{\"email\":\""
            + email + "\",\"password\":\""
            + password + "\"}";
    Request request = new Request.Builder()
            .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))

    Call call = client.newCall(request);
    call.enqueue(new Callback() {
        public void onFailure(Call call, IOException e) {
            Log.d(TAG,"failed in callback");

        public void onResponse(Call call, Response response) throws IOException {
            try {
                //Response response = client.newCall(request).execute();
                mAuthResponse = response.body().string();
                Log.d(TAG,"response.body().string() was received.");
                if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            catch (IOException e){