Search in sources :

Example 26 with Request

use of com.tonyodev.fetch2.Request in project Android by Tracman-org.

the class LoginActivity method signInWithPassword.

public void signInWithPassword() {
    //Log.d(TAG, "signInWithPassword() called");
    // Get params from form
    EditText emailText = (EditText) findViewById(R.id.login_email);
    String email = emailText.getText().toString();
    EditText passwordText = (EditText) findViewById(R.id.login_password);
    String password = passwordText.getText().toString();
    // Build formdata
    RequestBody formData = new FormBody.Builder().add("email", email).add("password", password).build();
    // Build request
    Request request = new Request.Builder().url(SERVER_ADDRESS + "login/app").post(formData).build();
    // Send formdata to endpoint
    try {
        //Log.v(TAG, "Sending local login POST to server...");
        authenticateWithTracmanServer(request);
    } catch (Exception e) {
    //Log.e(TAG, "Error sending local login to backend:",e);
    }
}
Also used : EditText(android.widget.EditText) FormBody(okhttp3.FormBody) Request(okhttp3.Request) JSONException(org.json.JSONException) IOException(java.io.IOException) RequestBody(okhttp3.RequestBody)

Example 27 with Request

use of com.tonyodev.fetch2.Request in project Tusky by Vavassor.

the class OkHttpUtils method getUserAgentInterceptor.

/**
     * Add a custom User-Agent that contains Tusky & Android Version to all requests
     * Example:
     * User-Agent: Tusky/1.1.2 Android/5.0.2
     */
@NonNull
private static Interceptor getUserAgentInterceptor() {
    return new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            Request requestWithUserAgent = originalRequest.newBuilder().header("User-Agent", "Tusky/" + BuildConfig.VERSION_NAME + " Android/" + Build.VERSION.RELEASE).build();
            return chain.proceed(requestWithUserAgent);
        }
    };
}
Also used : Request(okhttp3.Request) Interceptor(okhttp3.Interceptor) NonNull(android.support.annotation.NonNull)

Example 28 with Request

use of com.tonyodev.fetch2.Request in project Tusky by Vavassor.

the class BaseActivity method createMastodonAPI.

protected void createMastodonAPI() {
    mastodonApiDispatcher = new Dispatcher();
    Gson gson = new GsonBuilder().registerTypeAdapter(Spanned.class, new SpannedTypeAdapter()).registerTypeAdapter(StringWithEmoji.class, new StringWithEmojiTypeAdapter()).create();
    OkHttpClient okHttpClient = OkHttpUtils.getCompatibleClientBuilder().addInterceptor(new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            Request.Builder builder = originalRequest.newBuilder();
            String accessToken = getAccessToken();
            if (accessToken != null) {
                builder.header("Authorization", String.format("Bearer %s", accessToken));
            }
            Request newRequest = builder.build();
            return chain.proceed(newRequest);
        }
    }).dispatcher(mastodonApiDispatcher).build();
    Retrofit retrofit = new Retrofit.Builder().baseUrl(getBaseUrl()).client(okHttpClient).addConverterFactory(GsonConverterFactory.create(gson)).build();
    mastodonAPI = retrofit.create(MastodonAPI.class);
}
Also used : OkHttpClient(okhttp3.OkHttpClient) GsonBuilder(com.google.gson.GsonBuilder) GsonBuilder(com.google.gson.GsonBuilder) SpannedTypeAdapter(com.keylesspalace.tusky.json.SpannedTypeAdapter) Request(okhttp3.Request) Gson(com.google.gson.Gson) IOException(java.io.IOException) Dispatcher(okhttp3.Dispatcher) Response(okhttp3.Response) Retrofit(retrofit2.Retrofit) StringWithEmojiTypeAdapter(com.keylesspalace.tusky.json.StringWithEmojiTypeAdapter) MastodonAPI(com.keylesspalace.tusky.network.MastodonAPI) Interceptor(okhttp3.Interceptor) StringWithEmoji(com.keylesspalace.tusky.json.StringWithEmoji)

Example 29 with Request

use of com.tonyodev.fetch2.Request in project Rocket.Chat.Android by RocketChat.

the class RxWebSocket method connect.

public ConnectableFlowable<RxWebSocketCallback.Base> connect(String url) {
    final Request request = new Request.Builder().url(url).build();
    return Flowable.create((FlowableOnSubscribe<RxWebSocketCallback.Base>) emitter -> httpClient.newWebSocket(request, new WebSocketListener() {

        @Override
        public void onOpen(WebSocket webSocket, Response response) {
            RxWebSocket.this.webSocket = webSocket;
            emitter.onNext(new RxWebSocketCallback.Open(RxWebSocket.this.webSocket, response));
        }

        @Override
        public void onFailure(WebSocket webSocket, Throwable err, Response response) {
            try {
                emitter.onError(new RxWebSocketCallback.Failure(webSocket, err, response));
            } catch (OnErrorNotImplementedException ex) {
                RCLog.w(ex, "OnErrorNotImplementedException ignored");
            }
        }

        @Override
        public void onMessage(WebSocket webSocket, String text) {
            emitter.onNext(new RxWebSocketCallback.Message(webSocket, text));
        }

        @Override
        public void onClosed(WebSocket webSocket, int code, String reason) {
            emitter.onNext(new RxWebSocketCallback.Close(webSocket, code, reason));
            emitter.onComplete();
        }
    }), BackpressureStrategy.BUFFER).publish();
}
Also used : FlowableOnSubscribe(io.reactivex.FlowableOnSubscribe) WebSocketListener(okhttp3.WebSocketListener) Request(okhttp3.Request) OnErrorNotImplementedException(io.reactivex.exceptions.OnErrorNotImplementedException) WebSocket(okhttp3.WebSocket) Response(okhttp3.Response)

Example 30 with Request

use of com.tonyodev.fetch2.Request in project Rocket.Chat.Android by RocketChat.

the class FileUploadingWithUfsObserver method onUpdateResults.

@Override
public void onUpdateResults(List<FileUploading> results) {
    if (results.isEmpty()) {
        return;
    }
    List<FileUploading> uploadingList = realmHelper.executeTransactionForReadResults(realm -> realm.where(FileUploading.class).equalTo(FileUploading.SYNC_STATE, SyncState.SYNCING).findAll());
    if (uploadingList.size() >= 1) {
        // do not upload multiple files simultaneously
        return;
    }
    RealmUser currentUser = realmHelper.executeTransactionForRead(realm -> RealmUser.queryCurrentUser(realm).findFirst());
    RealmSession session = realmHelper.executeTransactionForRead(realm -> RealmSession.queryDefaultSession(realm).findFirst());
    if (currentUser == null || session == null) {
        return;
    }
    final String cookie = String.format("rc_uid=%s; rc_token=%s", currentUser.getId(), session.getToken());
    FileUploading fileUploading = results.get(0);
    final String roomId = fileUploading.getRoomId();
    final String uplId = fileUploading.getUplId();
    final String filename = fileUploading.getFilename();
    final long filesize = fileUploading.getFilesize();
    final String mimeType = fileUploading.getMimeType();
    final Uri fileUri = Uri.parse(fileUploading.getUri());
    final String store = FileUploading.STORAGE_TYPE_GRID_FS.equals(fileUploading.getStorageType()) ? "rocketchat_uploads" : (FileUploading.STORAGE_TYPE_FILE_SYSTEM.equals(fileUploading.getStorageType()) ? "fileSystem" : null);
    realmHelper.executeTransaction(realm -> realm.createOrUpdateObjectFromJson(FileUploading.class, new JSONObject().put(FileUploading.ID, uplId).put(FileUploading.SYNC_STATE, SyncState.SYNCING))).onSuccessTask(_task -> methodCall.ufsCreate(filename, filesize, mimeType, store, roomId)).onSuccessTask(task -> {
        final JSONObject info = task.getResult();
        final String fileId = info.getString("fileId");
        final String token = info.getString("token");
        final String url = info.getString("url");
        final int bufSize = 16384;
        final byte[] buffer = new byte[bufSize];
        int offset = 0;
        final MediaType contentType = MediaType.parse(mimeType);
        try (InputStream inputStream = context.getContentResolver().openInputStream(fileUri)) {
            int read;
            while ((read = inputStream.read(buffer)) > 0) {
                offset += read;
                double progress = 1.0 * offset / filesize;
                Request request = new Request.Builder().url(url + "&progress=" + progress).header("Cookie", cookie).post(RequestBody.create(contentType, buffer, 0, read)).build();
                Response response = OkHttpHelper.getClientForUploadFile().newCall(request).execute();
                if (response.isSuccessful()) {
                    final JSONObject obj = new JSONObject().put(FileUploading.ID, uplId).put(FileUploading.UPLOADED_SIZE, offset);
                    realmHelper.executeTransaction(realm -> realm.createOrUpdateObjectFromJson(FileUploading.class, obj));
                } else {
                    return Task.forError(new Exception(response.message()));
                }
            }
        }
        return methodCall.ufsComplete(fileId, token, store);
    }).onSuccessTask(task -> methodCall.sendFileMessage(roomId, null, task.getResult())).onSuccessTask(task -> realmHelper.executeTransaction(realm -> realm.createOrUpdateObjectFromJson(FileUploading.class, new JSONObject().put(FileUploading.ID, uplId).put(FileUploading.SYNC_STATE, SyncState.SYNCED).put(FileUploading.ERROR, JSONObject.NULL)))).continueWithTask(task -> {
        if (task.isFaulted()) {
            RCLog.w(task.getError());
            return realmHelper.executeTransaction(realm -> realm.createOrUpdateObjectFromJson(FileUploading.class, new JSONObject().put(FileUploading.ID, uplId).put(FileUploading.SYNC_STATE, SyncState.FAILED).put(FileUploading.ERROR, task.getError().getMessage())));
        } else {
            return Task.forResult(null);
        }
    });
}
Also used : Context(android.content.Context) Realm(io.realm.Realm) Request(okhttp3.Request) RealmUser(chat.rocket.persistence.realm.models.ddp.RealmUser) RealmSession(chat.rocket.persistence.realm.models.internal.RealmSession) RealmResults(io.realm.RealmResults) Uri(android.net.Uri) RCLog(chat.rocket.android.log.RCLog) LogIfError(chat.rocket.android.helper.LogIfError) RequestBody(okhttp3.RequestBody) List(java.util.List) JSONObject(org.json.JSONObject) RealmHelper(chat.rocket.persistence.realm.RealmHelper) SyncState(chat.rocket.core.SyncState) Response(okhttp3.Response) FileUploading(chat.rocket.persistence.realm.models.internal.FileUploading) DDPClientRef(chat.rocket.android.service.DDPClientRef) Task(bolts.Task) OkHttpHelper(chat.rocket.android.helper.OkHttpHelper) MediaType(okhttp3.MediaType) InputStream(java.io.InputStream) FileUploadingHelper(chat.rocket.android.api.FileUploadingHelper) InputStream(java.io.InputStream) RealmUser(chat.rocket.persistence.realm.models.ddp.RealmUser) Request(okhttp3.Request) Uri(android.net.Uri) Response(okhttp3.Response) JSONObject(org.json.JSONObject) FileUploading(chat.rocket.persistence.realm.models.internal.FileUploading) MediaType(okhttp3.MediaType) RealmSession(chat.rocket.persistence.realm.models.internal.RealmSession)

Aggregations

Request (okhttp3.Request)1601 Response (okhttp3.Response)1009 IOException (java.io.IOException)519 Test (org.junit.Test)406 OkHttpClient (okhttp3.OkHttpClient)330 RequestBody (okhttp3.RequestBody)255 Call (okhttp3.Call)239 ResponseBody (okhttp3.ResponseBody)187 HttpUrl (okhttp3.HttpUrl)139 Callback (okhttp3.Callback)109 Map (java.util.Map)85 File (java.io.File)77 InputStream (java.io.InputStream)77 JSONObject (org.json.JSONObject)76 MediaType (okhttp3.MediaType)75 Buffer (okio.Buffer)73 List (java.util.List)71 Headers (okhttp3.Headers)71 FormBody (okhttp3.FormBody)64 HashMap (java.util.HashMap)63