Search in sources :

Example 51 with Callback

use of retrofit2.Callback in project retrofit by square.

the class BehaviorCall method execute.

@Override
public Response<T> execute() throws IOException {
    final AtomicReference<Response<T>> responseRef = new AtomicReference<>();
    final AtomicReference<Throwable> failureRef = new AtomicReference<>();
    final CountDownLatch latch = new CountDownLatch(1);
    enqueue(new Callback<T>() {

        @Override
        public void onResponse(Call<T> call, Response<T> response) {
            responseRef.set(response);
            latch.countDown();
        }

        @Override
        public void onFailure(Call<T> call, Throwable t) {
            failureRef.set(t);
            latch.countDown();
        }
    });
    try {
        latch.await();
    } catch (InterruptedException e) {
        throw new IOException("canceled");
    }
    Response<T> response = responseRef.get();
    if (response != null)
        return response;
    Throwable failure = failureRef.get();
    if (failure instanceof RuntimeException)
        throw (RuntimeException) failure;
    if (failure instanceof IOException)
        throw (IOException) failure;
    throw new RuntimeException(failure);
}
Also used : AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) Response(retrofit2.Response)

Example 52 with Callback

use of retrofit2.Callback in project retrofit by square.

the class CallsTest method deferredThrowEnqueue.

@Test
public void deferredThrowEnqueue() {
    final IOException failure = new IOException("Hey");
    Call<Object> failing = Calls.defer(new Callable<Call<Object>>() {

        @Override
        public Call<Object> call() throws Exception {
            throw failure;
        }
    });
    final AtomicReference<Throwable> failureRef = new AtomicReference<>();
    failing.enqueue(new Callback<Object>() {

        @Override
        public void onResponse(Call<Object> call, Response<Object> response) {
            fail();
        }

        @Override
        public void onFailure(Call<Object> call, Throwable t) {
            failureRef.set(t);
        }
    });
    assertSame(failure, failureRef.get());
}
Also used : Call(retrofit2.Call) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) IOException(java.io.IOException) Test(org.junit.Test)

Example 53 with Callback

use of retrofit2.Callback in project plaid by nickbutcher.

the class DesignerNewsStory method setupCommentField.

@NonNull
private View setupCommentField() {
    View enterCommentView = getLayoutInflater().inflate(R.layout.designer_news_enter_comment, commentsList, false);
    enterComment = (EditText) enterCommentView.findViewById(R.id.comment);
    postComment = (ImageButton) enterCommentView.findViewById(R.id.post_comment);
    postComment.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (designerNewsPrefs.isLoggedIn()) {
                if (TextUtils.isEmpty(enterComment.getText()))
                    return;
                enterComment.setEnabled(false);
                postComment.setEnabled(false);
                final Call<Comment> comment = designerNewsPrefs.getApi().comment(story.id, enterComment.getText().toString());
                comment.enqueue(new Callback<Comment>() {

                    @Override
                    public void onResponse(Call<Comment> call, Response<Comment> response) {
                        enterComment.getText().clear();
                        enterComment.setEnabled(true);
                        postComment.setEnabled(true);
                        commentsAdapter.addComment(response.body());
                    }

                    @Override
                    public void onFailure(Call<Comment> call, Throwable t) {
                        Toast.makeText(getApplicationContext(), "Failed to post comment :(", Toast.LENGTH_SHORT).show();
                        enterComment.setEnabled(true);
                        postComment.setEnabled(true);
                    }
                });
            } else {
                needsLogin(postComment, 0);
            }
            enterComment.clearFocus();
        }
    });
    enterComment.setOnFocusChangeListener(enterCommentFocus);
    return enterCommentView;
}
Also used : Response(retrofit2.Response) Call(retrofit2.Call) SharedElementCallback(android.app.SharedElementCallback) Callback(retrofit2.Callback) ImageView(android.widget.ImageView) BindView(butterknife.BindView) View(android.view.View) AuthorTextView(io.plaidapp.ui.widget.AuthorTextView) TextView(android.widget.TextView) PinnedOffsetView(io.plaidapp.ui.widget.PinnedOffsetView) RecyclerView(android.support.v7.widget.RecyclerView) NonNull(android.support.annotation.NonNull)

Example 54 with Callback

use of retrofit2.Callback in project WordPress-Android by wordpress-mobile.

the class GravatarApi method uploadGravatar.

public static void uploadGravatar(final File file, final String email, final String accessToken, final GravatarUploadListener gravatarUploadListener) {
    Request request = prepareGravatarUpload(email, file);
    createClient(accessToken).newCall(request).enqueue(new Callback() {

        @Override
        public void onResponse(Call call, final Response response) throws IOException {
            if (!response.isSuccessful()) {
                Map<String, Object> properties = new HashMap<>();
                properties.put("network_response_code", response.code());
                // response's body can only be read once so, keep it in a local variable
                String responseBody;
                try {
                    responseBody = response.body().string();
                } catch (IOException e) {
                    responseBody = "null";
                }
                properties.put("network_response_body", responseBody);
                AnalyticsTracker.track(AnalyticsTracker.Stat.ME_GRAVATAR_UPLOAD_UNSUCCESSFUL, properties);
                AppLog.w(AppLog.T.API, "Network call unsuccessful trying to upload Gravatar: " + responseBody);
            }
            new Handler(Looper.getMainLooper()).post(new Runnable() {

                @Override
                public void run() {
                    if (response.isSuccessful()) {
                        gravatarUploadListener.onSuccess();
                    } else {
                        gravatarUploadListener.onError();
                    }
                }
            });
        }

        @Override
        public void onFailure(okhttp3.Call call, final IOException e) {
            Map<String, Object> properties = new HashMap<>();
            properties.put("network_exception_class", e != null ? e.getClass().getCanonicalName() : "null");
            properties.put("network_exception_message", e != null ? e.getMessage() : "null");
            AnalyticsTracker.track(AnalyticsTracker.Stat.ME_GRAVATAR_UPLOAD_EXCEPTION, properties);
            CrashlyticsUtils.logException(e, AppLog.T.API, "Network call failure trying to upload Gravatar!");
            AppLog.w(AppLog.T.API, "Network call failure trying to upload Gravatar!" + (e != null ? e.getMessage() : "null"));
            new Handler(Looper.getMainLooper()).post(new Runnable() {

                @Override
                public void run() {
                    gravatarUploadListener.onError();
                }
            });
        }
    });
}
Also used : Call(okhttp3.Call) Request(okhttp3.Request) Handler(android.os.Handler) IOException(java.io.IOException) Response(okhttp3.Response) Callback(okhttp3.Callback) Call(okhttp3.Call) HashMap(java.util.HashMap) Map(java.util.Map)

Example 55 with Callback

use of retrofit2.Callback in project Gradle-demo by Arisono.

the class OkhttpUtilsMain method sendSysResquest.

/**
	 * Okhttp 异步请求
	 */
public static void sendSysResquest() {
    RequestBody formBody = new FormBody.Builder().add("username", "123").add("password", "df13edafsdddsads").build();
    OkHttpClient client = new OkHttpClient.Builder().connectTimeout(5, TimeUnit.SECONDS).readTimeout(5, TimeUnit.SECONDS).build();
    Request request = new Request.Builder().url("http://localhost:8080/spring-mvc-showcase/client/info").header("cookie", "JSESSIONID=EB36DE5E50E342D86C55DAE0CDDD4F6D").addHeader("content-type", "text/html;charset:utf-8").post(formBody).build();
    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (response.isSuccessful()) {
                String json = response.body().string();
                System.out.println(json);
            } else {
                System.out.println(JSON.toJSONString(response.code()));
            }
        }

        @Override
        public void onFailure(Call call, IOException e) {
            System.out.println(ExceptionUtils.printExceptionStack(e));
            if (e instanceof ConnectException) {
                System.out.println("服务器拒绝访问!");
            } else if (e instanceof SocketTimeoutException) {
                System.out.println("超时响应!");
            }
        }
    });
}
Also used : Call(okhttp3.Call) OkHttpClient(okhttp3.OkHttpClient) FormBody(okhttp3.FormBody) Request(okhttp3.Request) IOException(java.io.IOException) Response(okhttp3.Response) Callback(okhttp3.Callback) SocketTimeoutException(java.net.SocketTimeoutException) RequestBody(okhttp3.RequestBody) ConnectException(java.net.ConnectException)

Aggregations

IOException (java.io.IOException)51 Response (okhttp3.Response)46 Call (okhttp3.Call)44 Callback (okhttp3.Callback)44 Request (okhttp3.Request)41 RequestBody (okhttp3.RequestBody)25 Call (retrofit2.Call)17 Callback (retrofit2.Callback)15 Test (org.junit.Test)14 Response (retrofit2.Response)14 CountDownLatch (java.util.concurrent.CountDownLatch)13 FormBody (okhttp3.FormBody)12 ToStringConverterFactory (retrofit2.helpers.ToStringConverterFactory)12 OkHttpClient (okhttp3.OkHttpClient)11 AtomicReference (java.util.concurrent.atomic.AtomicReference)10 ResponseBody (okhttp3.ResponseBody)10 MockResponse (okhttp3.mockwebserver.MockResponse)10 Retrofit (retrofit2.Retrofit)9 TextView (android.widget.TextView)6 HttpUrl (okhttp3.HttpUrl)6