Example usage for android.util Base64 encodeToString

List of usage examples for android.util Base64 encodeToString

Introduction

In this page you can find the example usage for android.util Base64 encodeToString.

Prototype

public static String encodeToString(byte[] input, int flags) 

Source Link

Document

Base64-encode the given data and return a newly allocated String with the result.

Usage

From source file:com.danga.camli.UploadThread.java

private String getBasicAuthHeaderValue() {
    return "Basic " + Base64.encodeToString((USERNAME + ":" + mPassword).getBytes(), Base64.NO_WRAP);
}

From source file:eu.codeplumbers.cosi.services.CosiLoyaltyCardService.java

@Override
protected void onHandleIntent(Intent intent) {
    // Do the task here
    Log.i(CosiLoyaltyCardService.class.getName(), "Cosi Service running");

    // Release the wake lock provided by the WakefulBroadcastReceiver.
    WakefulBroadcastReceiver.completeWakefulIntent(intent);

    Device device = Device.registeredDevice();

    // cozy register device url
    designUrl = device.getUrl() + "/ds-api/request/loyaltycard/all/";
    syncUrl = device.getUrl() + "/ds-api/data/";

    // concatenate username and password with colon for authentication
    final String credentials = device.getLogin() + ":" + device.getPassword();
    authHeader = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);

    showNotification();/*  ww w .ja  va 2  s. c  om*/

    if (isNetworkAvailable()) {
        try {
            EventBus.getDefault()
                    .post(new LoyaltyCardSyncEvent(SYNC_MESSAGE, "Getting loyalty cards from Cozy..."));
            getRemoteLoyaltyCards();
            mNotifyManager.cancel(notification_id);
            sendChangesToCozy();
            EventBus.getDefault().post(new LoyaltyCardSyncEvent(REFRESH, "Sync OK"));
        } catch (Exception e) {
            e.printStackTrace();
            mSyncRunning = false;
            EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        }
    } else {
        mSyncRunning = false;
        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, "No Internet connection"));
        mBuilder.setContentText("Sync failed because no Internet connection was available");
        mNotifyManager.notify(notification_id, mBuilder.build());
    }
}

From source file:com.liato.bankdroid.banking.banks.ica.ICA.java

public Urllib login() throws LoginException, BankException {
    urlopen = new Urllib(context, CertificateReader.getCertificates(context, R.raw.cert_ica));
    urlopen.addHeader("Accept", "application/json;charset=UTF-8");
    urlopen.addHeader("Content-Type", "application/json;charset=UTF-8");
    urlopen.addHeader("Authorization",
            "Basic " + Base64.encodeToString(new String(username + ":" + password).getBytes(), Base64.NO_WRAP));

    try {/*  w  ww .ja  v a  2 s.  c  o m*/
        HttpResponse httpResponse = urlopen.openAsHttpResponse(API_URL + "login",
                new ArrayList<NameValuePair>(), false);
        if (httpResponse.getStatusLine().getStatusCode() == 401) {
            LoginError le = readJsonValue(httpResponse, LoginError.class);
            if (le != null && "UsernamePassword".equals(le.getMessageCode())) {
                if (!TextUtils.isEmpty(le.getMessage())) {
                    throw new LoginException(le.getMessage());
                } else {
                    throw new LoginException(context.getText(R.string.invalid_username_password).toString());
                }
            } else {
                throw new BankException(context.getText(R.string.invalid_username_password).toString());
            }
        }

        for (Map.Entry<String, String> entry : mHeaders.entrySet()) {
            Header header = httpResponse.getFirstHeader(entry.getKey());
            if (header == null || TextUtils.isEmpty(header.getValue())) {
                throw new BankException(
                        context.getString(R.string.unable_to_find).toString() + " " + entry.getKey());
            }
            mHeaders.put(entry.getKey(), header.getValue());
        }

        urlopen.addHeader(AUTHENTICATION_TICKET_HEADER, mHeaders.get(AUTHENTICATION_TICKET_HEADER));
        httpResponse = urlopen.openAsHttpResponse(API_URL + "user/minasidor", new ArrayList<NameValuePair>(),
                false);
        Overview overview = readJsonValue(httpResponse, Overview.class);

        if (overview == null) {
            throw new BankException(context.getString(R.string.unable_to_find) + " overview.");
        }

        if (!TextUtils.isEmpty(overview.getAccountName())) {
            Account account = new Account(overview.getAccountName(),
                    BigDecimal.valueOf(overview.getAvailableAmount()), overview.getAccountNumber());
            balance = balance.add(account.getBalance());
            accounts.add(account);
            List<Transaction> transactions = new ArrayList<Transaction>();
            for (com.liato.bankdroid.banking.banks.ica.model.Transaction t : overview.getTransactions()) {
                transactions.add(new Transaction(t.getTransactionDate(), t.getDescription(),
                        BigDecimal.valueOf(t.getAmount())));
            }
            account.setTransactions(transactions);
        }
        for (com.liato.bankdroid.banking.banks.ica.model.Account a : overview.getAccounts()) {
            Account account = new Account(a.getName(), BigDecimal.valueOf(a.getAvailableAmount()),
                    a.getAccountNumber());
            balance = balance.add(account.getBalance());
            accounts.add(account);
            List<Transaction> transactions = new ArrayList<Transaction>();
            for (com.liato.bankdroid.banking.banks.ica.model.Transaction t : a.getTransactions()) {
                transactions.add(new Transaction(t.getTransactionDate(), t.getDescription(),
                        BigDecimal.valueOf(t.getAmount())));
            }
            account.setTransactions(transactions);
        }

        Account account = new Account("Erhllen bonus i r", BigDecimal.valueOf(overview.getAcquiredBonus()),
                "bonus");
        account.setType(Account.OTHER);
        accounts.add(account);
        account = new Account("rets totala inkp p ICA",
                BigDecimal.valueOf(overview.getYearlyTotalPurchased()), "totalpurchased");
        account.setType(Account.OTHER);
        accounts.add(account);

        if (accounts.isEmpty()) {
            throw new BankException(res.getText(R.string.no_accounts_found).toString());
        }

        urlopen.addHeader(LOGOUT_KEY_HEADER, mHeaders.get(LOGOUT_KEY_HEADER));
        httpResponse = urlopen.openAsHttpResponse(API_URL + "logout", new ArrayList<NameValuePair>(), false);
        httpResponse.getStatusLine();
    } catch (JsonParseException e) {
        e.printStackTrace();
        throw new BankException(e.getMessage());
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        throw new BankException(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        throw new BankException(e.getMessage());
    }
    return urlopen;
}

From source file:org.andstatus.app.net.http.HttpConnectionBasic.java

/**
 * Get the HTTP digest authentication. Uses Base64 to encode credentials.
 * //from w w  w  .  ja v a  2  s  .  co m
 * @return String
 */
private String getCredentials() {
    return Base64.encodeToString((data.accountUsername + ":" + mPassword).getBytes(Charset.forName("UTF-8")),
            Base64.NO_WRAP + Base64.NO_PADDING);
}

From source file:com.example.socketmobile.android.warrantychecker.network.WarrantyCheck.java

private Object fetchWarranty(String id, String authString, String query) throws IOException {
    InputStream is = null;/*from w w w . j  a  v  a2s  .c  o  m*/
    RegistrationApiResponse result = null;
    RegistrationApiErrorResponse errorResult = null;
    String authHeader = "Basic " + Base64.encodeToString(authString.getBytes(), Base64.NO_WRAP);

    try {
        URL url = new URL(baseUrl + id + "?" + query);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(10000 /* milliseconds */);
        //conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setDoOutput(false);

        conn.connect();
        int response = conn.getResponseCode();
        Log.d(TAG, "WarrantyCheck query responded: " + response);
        switch (response / 100) {
        case 2:
            is = conn.getInputStream();
            RegistrationApiResponse.Reader reader = new RegistrationApiResponse.Reader();
            result = reader.readJsonStream(is);
            break;
        case 4:
        case 5:
            is = conn.getErrorStream();
            RegistrationApiErrorResponse.Reader errorReader = new RegistrationApiErrorResponse.Reader();
            errorResult = errorReader.readErrorJsonStream(is);
            break;
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        return null;
    } finally {
        if (is != null) {
            is.close();
        }
    }
    return (result != null) ? result : errorResult;
}

From source file:com.yanzhenjie.nohttp.cache.CacheEntity.java

/**
 * @return the data.
 */
public String getDataBase64() {
    return Base64.encodeToString(data, Base64.DEFAULT);
}

From source file:org.xwiki.android.authenticator.rest.XWikiConnector.java

public static HttpGet createHtpGet(String url, String user, String pass) {
    HttpGet httpGet = new HttpGet(url);

    httpGet.addHeader("Authorization",
            "Basic " + Base64.encodeToString((user + ':' + pass).getBytes(), Base64.NO_WRAP));

    HttpParams params = new BasicHttpParams();
    params.setParameter("username", user);
    params.setParameter("password", pass);
    httpGet.setParams(params);/*from   w  ww  . j  ava  2 s  . c  o m*/
    httpGet.addHeader("Accept", "application/xml");

    return httpGet;
}

From source file:eu.codeplumbers.cosi.services.CosiFileService.java

@Override
protected void onHandleIntent(Intent intent) {
    // Do the task here
    Log.i(CosiFileService.class.getName(), "Cosi Service running");

    // Release the wake lock provided by the WakefulBroadcastReceiver.
    WakefulBroadcastReceiver.completeWakefulIntent(intent);

    allFiles = new ArrayList<>();

    Device device = Device.registeredDevice();

    // cozy register device url
    folderUrl = device.getUrl() + "/ds-api/request/folder/cosiall/";
    fileUrl = device.getUrl() + "/ds-api/request/file/cosiall/";

    // concatenate username and password with colon for authentication
    final String credentials = device.getLogin() + ":" + device.getPassword();
    authHeader = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);

    showNotification();//from  ww  w  . j a  va 2s . c o m

    if (isNetworkAvailable()) {
        try {
            // read local sms log first
            getAllRemoteFolders();
            getAllRemoteFiles();

            mBuilder.setContentText(getString(R.string.lbl_sms_sync_done));
            mBuilder.setProgress(0, 0, false);
            mNotifyManager.notify(notification_id, mBuilder.build());

            if (!allFiles.isEmpty()) {
                mNotifyManager.cancel(notification_id);
                EventBus.getDefault().post(new FileSyncEvent(REFRESH, "Sync OK"));
            } else {
                EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, "Sync failed"));
            }

        } catch (Exception e) {
            e.printStackTrace();
            mSyncRunning = false;
            EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        }
    } else {
        mSyncRunning = false;
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, "No Internet connection"));
        mBuilder.setContentText("Sync failed because no Internet connection was available");
        mNotifyManager.notify(notification_id, mBuilder.build());
    }
}

From source file:eu.codeplumbers.cosi.services.CosiExpenseService.java

@Override
protected void onHandleIntent(Intent intent) {
    // Do the task here
    Log.i(CosiExpenseService.class.getName(), "Cosi Service running");

    // Release the wake lock provided by the WakefulBroadcastReceiver.
    WakefulBroadcastReceiver.completeWakefulIntent(intent);

    // delete local expenses
    new Delete().from(Receipt.class).execute();
    new Delete().from(Expense.class).execute();

    Device device = Device.registeredDevice();

    // cozy register device url
    designUrl = device.getUrl() + "/ds-api/request/expense/all/";
    syncUrl = device.getUrl() + "/ds-api/data/";

    // concatenate username and password with colon for authentication
    final String credentials = device.getLogin() + ":" + device.getPassword();
    authHeader = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);

    showNotification();/*from  www .  j av a 2s.c  o m*/

    if (isNetworkAvailable()) {
        try {
            EventBus.getDefault().post(new ExpenseSyncEvent(SYNC_MESSAGE, "Getting expenses from Cozy..."));
            getRemoteExpenses();
            mNotifyManager.cancel(notification_id);
            sendChangesToCozy();
            EventBus.getDefault().post(new ExpenseSyncEvent(REFRESH, "Sync OK"));
        } catch (Exception e) {
            e.printStackTrace();
            mSyncRunning = false;
            EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        }
    } else {
        mSyncRunning = false;
        EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, "No Internet connection"));
        mBuilder.setContentText("Sync failed because no Internet connection was available");
        mNotifyManager.notify(notification_id, mBuilder.build());
    }
}

From source file:com.ibm.pickmeup.utils.MessageFactory.java

/**
 * Method to create a message with the passenger's photo encoded as base64 string
 *
 * @return msg string representation of the JSONObject
 *//*from w ww .  j a v a2s. c  o  m*/
public String getPassengerPhotoMessage() {
    Log.d(TAG, ".getPassengerPhotoMessage() entered");
    PickMeUpApplication app = (PickMeUpApplication) context.getApplicationContext();
    Bitmap passengerPhoto = app.getPassengerPhoto();
    ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
    passengerPhoto.compress(Bitmap.CompressFormat.PNG, 100, byteOutputStream);
    String passengerPhotoAsBase64String = Base64.encodeToString(byteOutputStream.toByteArray(), Base64.DEFAULT);

    JSONObject msg = new JSONObject();
    try {
        msg.put(Constants.URL, Constants.BASE64_PHOTO_PREFIX + passengerPhotoAsBase64String);
    } catch (JSONException e) {
        Log.d(TAG, ".getPassengerPhotoMessage() - Exception caught while generating a JSON object",
                e.getCause());
    }
    return msg.toString();
}