Search in sources :

Example 11 with Callback

use of retrofit2.Callback in project OkHttp3 by MrZhousf.

the class HttpHelper method doRequestAsync.

/**
     * 异步请求
     */
void doRequestAsync(final OkHttpHelper helper) {
    final HttpInfo info = httpInfo;
    final BaseCallback callback = helper.getCallback();
    Request request = helper.getRequest();
    String url = info.getUrl();
    if (!checkUrl(url)) {
        //主线程回调
        Message msg = new CallbackMessage(OkMainHandler.RESPONSE_CALLBACK, callback, retInfo(info, HttpInfo.CheckURL), requestTag, null).build();
        OkMainHandler.getInstance().sendMessage(msg);
        return;
    }
    request = request == null ? buildRequest(info, helper.getRequestMethod(), helper.getProgressCallback()) : request;
    showUrlLog(request);
    Call call = httpClient.newCall(request);
    BaseActivityLifecycleCallbacks.putCall(requestTag, call);
    call.enqueue(new Callback() {

        @Override
        public void onFailure(Call call, IOException e) {
            //主线程回调
            int code = HttpInfo.CheckNet;
            if (e instanceof UnknownHostException) {
                if (!helperInfo.getOkHttpUtil().isNetworkAvailable()) {
                    code = HttpInfo.CheckNet;
                } else {
                    code = HttpInfo.CheckURL;
                }
            } else if (e instanceof SocketTimeoutException) {
                if (null != e.getMessage()) {
                    if (e.getMessage().contains("failed to connect to"))
                        code = HttpInfo.ConnectionTimeOut;
                    if (e.getMessage().equals("timeout"))
                        code = HttpInfo.WriteAndReadTimeOut;
                }
            }
            Message msg = new CallbackMessage(OkMainHandler.RESPONSE_CALLBACK, callback, retInfo(info, code, "[" + e.getMessage() + "]"), requestTag, call).build();
            OkMainHandler.getInstance().sendMessage(msg);
        }

        @Override
        public void onResponse(Call call, Response res) throws IOException {
            //主线程回调
            Message msg = new CallbackMessage(OkMainHandler.RESPONSE_CALLBACK, callback, dealResponse(helper, res, call), requestTag, call).build();
            OkMainHandler.getInstance().sendMessage(msg);
        }
    });
}
Also used : Call(okhttp3.Call) UploadMessage(com.okhttplib.bean.UploadMessage) CallbackMessage(com.okhttplib.bean.CallbackMessage) DownloadMessage(com.okhttplib.bean.DownloadMessage) Message(android.os.Message) UnknownHostException(java.net.UnknownHostException) CallbackMessage(com.okhttplib.bean.CallbackMessage) Request(okhttp3.Request) IOException(java.io.IOException) HttpInfo(com.okhttplib.HttpInfo) Response(okhttp3.Response) ProgressCallback(com.okhttplib.callback.ProgressCallback) Callback(okhttp3.Callback) BaseCallback(com.okhttplib.callback.BaseCallback) SocketTimeoutException(java.net.SocketTimeoutException) BaseCallback(com.okhttplib.callback.BaseCallback)

Example 12 with Callback

use of retrofit2.Callback in project yyl_example by Relucent.

the class OkhttpTest2 method main.

public static void main(String[] args) throws IOException {
    OkHttpClient client;
    (client = //
    new OkHttpClient.Builder().build()).newCall(//
    new Request.Builder().url(//
    "https://www.baidu.com/").header("Connection", //close | keep-alive
    "close").get().build()).enqueue(new Callback() {

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            System.out.println(response.body().string());
        }

        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
        }
    });
    //应用关闭时候需要关闭线程池
    client.dispatcher().executorService().shutdown();
}
Also used : Response(okhttp3.Response) Call(okhttp3.Call) OkHttpClient(okhttp3.OkHttpClient) Callback(okhttp3.Callback) IOException(java.io.IOException)

Example 13 with Callback

use of retrofit2.Callback in project Tusky by Vavassor.

the class BaseActivity method enablePushNotifications.

protected void enablePushNotifications() {
    Callback<ResponseBody> callback = new Callback<ResponseBody>() {

        @Override
        public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
            if (response.isSuccessful()) {
                pushNotificationClient.subscribeToTopic(getPushNotificationTopic());
                pushNotificationClient.connect(BaseActivity.this);
            } else {
                onEnablePushNotificationsFailure(response.message());
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            onEnablePushNotificationsFailure(t.getMessage());
        }
    };
    String deviceToken = pushNotificationClient.getDeviceToken();
    Session session = new Session(getDomain(), getAccessToken(), deviceToken);
    tuskyApi.register(session).enqueue(callback);
}
Also used : Response(okhttp3.Response) Call(retrofit2.Call) Callback(retrofit2.Callback) ResponseBody(okhttp3.ResponseBody) Session(com.keylesspalace.tusky.entity.Session)

Example 14 with Callback

use of retrofit2.Callback in project Tusky by Vavassor.

the class LoginActivity method onStart.

@Override
protected void onStart() {
    super.onStart();
    /* Check if we are resuming during authorization by seeing if the intent contains the
         * redirect that was given to the server. If so, its response is here! */
    Uri uri = getIntent().getData();
    String redirectUri = getOauthRedirectUri();
    preferences = getSharedPreferences(getString(R.string.preferences_file_key), Context.MODE_PRIVATE);
    if (preferences.getString("accessToken", null) != null && preferences.getString("domain", null) != null) {
        // We are already logged in, go to MainActivity
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
        return;
    }
    if (uri != null && uri.toString().startsWith(redirectUri)) {
        // This should either have returned an authorization code or an error.
        String code = uri.getQueryParameter("code");
        String error = uri.getQueryParameter("error");
        if (code != null) {
            /* During the redirect roundtrip this Activity usually dies, which wipes out the
                 * instance variables, so they have to be recovered from where they were saved in
                 * SharedPreferences. */
            domain = preferences.getString("domain", null);
            clientId = preferences.getString("clientId", null);
            clientSecret = preferences.getString("clientSecret", null);
            setLoading(true);
            /* Since authorization has succeeded, the final step to log in is to exchange
                 * the authorization code for an access token. */
            Callback<AccessToken> callback = new Callback<AccessToken>() {

                @Override
                public void onResponse(Call<AccessToken> call, Response<AccessToken> response) {
                    if (response.isSuccessful()) {
                        onLoginSuccess(response.body().accessToken);
                    } else {
                        setLoading(false);
                        editText.setError(getString(R.string.error_retrieving_oauth_token));
                        Log.e(TAG, String.format("%s %s", getString(R.string.error_retrieving_oauth_token), response.message()));
                    }
                }

                @Override
                public void onFailure(Call<AccessToken> call, Throwable t) {
                    setLoading(false);
                    editText.setError(getString(R.string.error_retrieving_oauth_token));
                    Log.e(TAG, String.format("%s %s", getString(R.string.error_retrieving_oauth_token), t.getMessage()));
                }
            };
            getApiFor(domain).fetchOAuthToken(clientId, clientSecret, redirectUri, code, "authorization_code").enqueue(callback);
        } else if (error != null) {
            /* Authorization failed. Put the error response where the user can read it and they
                 * can try again. */
            setLoading(false);
            editText.setError(getString(R.string.error_authorization_denied));
            Log.e(TAG, getString(R.string.error_authorization_denied) + error);
        } else {
            setLoading(false);
            // This case means a junk response was received somehow.
            editText.setError(getString(R.string.error_authorization_unknown));
        }
    }
}
Also used : Response(retrofit2.Response) Call(retrofit2.Call) Callback(retrofit2.Callback) AccessToken(com.keylesspalace.tusky.entity.AccessToken) CustomTabsIntent(android.support.customtabs.CustomTabsIntent) Intent(android.content.Intent) Uri(android.net.Uri)

Example 15 with Callback

use of retrofit2.Callback in project Android by Tracman-org.

the class LoginActivity method authenticateWithTracmanServer.

private void authenticateWithTracmanServer(final Request request) throws Exception {
    // Needed to support TLS 1.1 and 1.2
    //		TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
    //				TrustManagerFactory.getDefaultAlgorithm());
    //		trustManagerFactory.init((KeyStore) null);
    //		TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
    //		if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
    //			throw new IllegalStateException("Unexpected default trust managers:"
    //					+ Arrays.toString(trustManagers));
    //		}
    //		X509TrustManager trustManager = (X509TrustManager) trustManagers[0];
    OkHttpClient client = new OkHttpClient.Builder().build();
    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onFailure(Call call, IOException e) {
            //Log.e(TAG, "Failed to connect to Tracman server!");
            showError(R.string.server_connection_error);
            e.printStackTrace();
        }

        @Override
        public void onResponse(Call call, Response res) throws IOException {
            if (!res.isSuccessful()) {
                showError(R.string.login_no_user_error);
                res.body().close();
                throw new IOException("Unexpected code: " + res);
            } else {
                //Log.d(TAG, "Response code: " + res.code());
                String userString = res.body().string();
                System.out.println("Full response: " + userString);
                String userID, userName, userSK;
                try {
                    JSONObject user = new JSONObject(userString);
                    userID = user.getString("_id");
                    userName = user.getString("name");
                    userSK = user.getString("sk32");
                //Log.v(TAG, "User retrieved with ID: " + userID);
                } catch (JSONException e) {
                    //Log.e(TAG, "Unable to parse user JSON: ", e);
                    //Log.e(TAG, "JSON String used: " + userString);
                    userID = null;
                    userName = null;
                    userSK = null;
                }
                // Save user as loggedInUser
                SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                SharedPreferences.Editor editor = sharedPref.edit();
                editor.putString("loggedInUser", userString);
                editor.putString("loggedInUserId", userID);
                editor.putString("loggedInUserName", userName);
                editor.putString("loggedInUserSk", userSK);
                editor.commit();
                startActivityForResult(new Intent(LoginActivity.this, SettingsActivity.class), SIGN_OUT);
            }
        }
    });
}
Also used : Call(okhttp3.Call) OkHttpClient(okhttp3.OkHttpClient) SharedPreferences(android.content.SharedPreferences) JSONException(org.json.JSONException) Intent(android.content.Intent) IOException(java.io.IOException) Response(okhttp3.Response) Callback(okhttp3.Callback) ResultCallback(com.google.android.gms.common.api.ResultCallback) JSONObject(org.json.JSONObject)

Aggregations

IOException (java.io.IOException)46 Response (okhttp3.Response)43 Call (okhttp3.Call)41 Callback (okhttp3.Callback)41 Request (okhttp3.Request)38 RequestBody (okhttp3.RequestBody)24 Call (retrofit2.Call)16 Test (org.junit.Test)14 Callback (retrofit2.Callback)14 CountDownLatch (java.util.concurrent.CountDownLatch)13 Response (retrofit2.Response)13 FormBody (okhttp3.FormBody)12 ToStringConverterFactory (retrofit2.helpers.ToStringConverterFactory)12 AtomicReference (java.util.concurrent.atomic.AtomicReference)10 MockResponse (okhttp3.mockwebserver.MockResponse)10 ResponseBody (okhttp3.ResponseBody)8 OkHttpClient (okhttp3.OkHttpClient)7 Retrofit (retrofit2.Retrofit)7 HttpUrl (okhttp3.HttpUrl)6 Intent (android.content.Intent)5