Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

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 MEDIA_TYPE_MARKDOWN
            = MediaType.parse("text/plain; charset=utf-8");

    OkHttpClient client = new OkHttpClient();

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


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

        @Override
        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){
                alertUserAboutError();
            }
        }
    });