Example usage for android.net Uri.Builder toString

List of usage examples for android.net Uri.Builder toString

Introduction

In this page you can find the example usage for android.net Uri.Builder toString.

Prototype

public abstract String toString();

Source Link

Document

Returns the encoded string representation of this URI.

Usage

From source file:io.github.protino.codewatch.remote.FetchLeaderBoardData.java

public int fetchUserRank() {
    AccessToken accessToken = CacheUtils.getAccessToken(context);
    if (accessToken == null) {
        return -1;
    }//  ww w.  j  a  v a 2s  .com

    HttpsURLConnection urlConnection = null;
    BufferedReader reader = null;

    String jsonStr;
    try {

        final String LEADER_PATH = "leaders";
        final String API_SUFFIX = "api/v1";
        final String CLIENT_SECRET = "secret";
        final String APP_SECRET = "app_secret";
        final String ACCESS_TOKEN = "token";

        Uri.Builder builder;

        builder = Uri.parse(Constants.WAKATIME_BASE_URL).buildUpon();
        builder.appendPath(API_SUFFIX).appendPath(LEADER_PATH)
                .appendQueryParameter(APP_SECRET, BuildConfig.CLIENT_ID)
                .appendQueryParameter(CLIENT_SECRET, BuildConfig.CLIENT_SECRET)
                .appendQueryParameter(ACCESS_TOKEN, accessToken.getAccessToken()).build();

        URL url = new URL(builder.toString());

        // Create the request to Wakatime.com, and open the connection

        urlConnection = (HttpsURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();

        // Read the input stream into a string
        InputStream inputStream = urlConnection.getInputStream();
        StringBuilder buffer = new StringBuilder();
        if (inputStream == null) {
            return -1;
        }
        reader = new BufferedReader(new InputStreamReader(inputStream));

        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }

        if (buffer.length() == 0) {
            return -1;
        }
        jsonStr = buffer.toString();

        JSONObject currentUser = new JSONObject(jsonStr).getJSONObject("current_user");
        if (currentUser == null) {
            return -1;
        } else {
            //if is a new user, it'll result throw JSONException, because rank=null
            return currentUser.getInt("rank");
        }

    } catch (IOException e) {
        Timber.e(e, "IO Error");
        return -1;
    } catch (JSONException e) {
        Timber.e(e, "JSON error");
        return -1;
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
                Timber.e(e, "Error closing stream");
            }
        }
    }

}

From source file:io.github.protino.codewatch.remote.FetchLeaderBoardData.java

private List<String> fetchLeaderBoardJson() {
    HttpsURLConnection urlConnection = null;
    BufferedReader reader = null;

    List<String> jsonDataList = new ArrayList<>();
    try {//from ww  w  .  j a  v a  2s.c  o m

        final String LEADER_PATH = "leaders";
        final String API_SUFFIX = "api/v1";
        final String API_KEY = "api_key";
        final String PAGE = "page";

        Uri.Builder builder;
        String jsonStr;

        int totalPages = -1;
        int page = 1;
        do {

            builder = Uri.parse(Constants.WAKATIME_BASE_URL).buildUpon();
            builder.appendPath(API_SUFFIX).appendPath(LEADER_PATH)
                    .appendQueryParameter(API_KEY, BuildConfig.API_KEY)
                    .appendQueryParameter(PAGE, String.valueOf(page)).build();

            URL url = new URL(builder.toString());

            // Create the request to Wakatime.com, and open the connection

            urlConnection = (HttpsURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();

            // Read the input stream into a string
            InputStream inputStream = urlConnection.getInputStream();
            StringBuilder buffer = new StringBuilder();
            if (inputStream == null) {
                return null;
            }
            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            if (buffer.length() == 0) {
                return null;
            }
            jsonStr = buffer.toString();
            jsonDataList.add(jsonStr);

            //parse totalpages
            if (totalPages == -1) {
                totalPages = new JSONObject(jsonStr).getInt("total_pages");
            }
            page++;
        } while (totalPages != page);
    } catch (IOException e) {
        Timber.e(e, "IO Error");
    } catch (JSONException e) {
        Timber.e(e, "JSON error");
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
                Timber.e(e, "Error closing stream");
            }
        }
    }
    return jsonDataList;
}

From source file:com.example.krishnateja.sunshine.FetchWeatherTask.java

@Override
protected String[] doInBackground(String... params) {

    // If there's no zip code, there's nothing to look up.  Verify size of params.
    if (params.length == 0) {
        return null;
    }/*from www  .  ja va  2s . c o m*/
    String locationQuery = params[0];

    // These two need to be declared outside the try/catch
    // so that they can be closed in the finally block.
    HttpURLConnection urlConnection = null;
    BufferedReader reader = null;

    // Will contain the raw JSON response as a string.
    String forecastJsonStr = null;

    String format = "json";
    String units = "metric";
    int numDays = 14;

    try {
        // Construct the URL for the OpenWeatherMap query
        // Possible parameters are avaiable at OWM's forecast API page, at
        // http://openweathermap.org/API#forecast
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(mContext);
        String zip = pref.getString(mContext.getString(R.string.key_editpref),
                mContext.getString(R.string.default_value_editpref));
        Uri.Builder builder = new Uri.Builder();
        builder.scheme("http").authority("api.openweathermap.org").appendPath("data").appendPath("2.5")
                .appendPath("forecast").appendPath("daily").appendQueryParameter("q", zip)
                .appendQueryParameter("mode", "json").appendQueryParameter("units", "metric")
                .appendQueryParameter("cnt", "7");
        //String url=builder.build().toString();
        //Log.v(LOG_TAG,"url->"+url);

        URL url = new URL(builder.toString());

        // Create the request to OpenWeatherMap, and open the connection
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();

        // Read the input stream into a String
        InputStream inputStream = urlConnection.getInputStream();
        StringBuffer buffer = new StringBuffer();
        if (inputStream == null) {
            // Nothing to do.
            return null;
        }
        reader = new BufferedReader(new InputStreamReader(inputStream));

        String line;
        while ((line = reader.readLine()) != null) {
            // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
            // But it does make debugging a *lot* easier if you print out the completed
            // buffer for debugging.
            buffer.append(line + "\n");
        }

        if (buffer.length() == 0) {
            // Stream was empty.  No point in parsing.
            return null;
        }
        forecastJsonStr = buffer.toString();
        Log.d(LOG_TAG, forecastJsonStr);
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error ", e);
        // If the code didn't successfully get the weather data, there's no point in attemping
        // to parse it.
        return null;
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException e) {
                Log.e(LOG_TAG, "Error closing stream", e);
            }
        }
    }

    try {
        return getWeatherDataFromJson(forecastJsonStr, locationQuery);
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    }
    // This will only happen if there was an error getting or parsing the forecast.
    return null;
}

From source file:com.gumgoose.app.quakebuddy.EarthquakeActivity.java

/**
 * @param id   is the ID of the Loader to be created
 * @param args are arguments supplied by the caller
 * @return     a new instance of the Loader to the LoaderManager
 */// w  w  w .java 2 s .c o m
@Override
public Loader<List<Quake>> onCreateLoader(int id, Bundle args) {
    // Loader created, obtain user's shared preferences
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

    String timePeriod = sharedPrefs.getString(getString(R.string.settings_time_period_key),
            getString(R.string.settings_time_period_default));

    String orderBy = sharedPrefs.getString(getString(R.string.settings_order_by_key),
            getString(R.string.settings_order_by_default));

    String minMagnitude = sharedPrefs.getString(getString(R.string.settings_min_magnitude_key),
            getString(R.string.settings_min_magnitude_default));

    // Create a URL builder object for querying the server
    Uri baseUri = Uri.parse(USGS_BASE_URL);
    Uri.Builder uriBuilder = baseUri.buildUpon();

    // Append query parameters to the URL builder
    uriBuilder.appendQueryParameter("format", "geojson");
    uriBuilder.appendQueryParameter("starttime", startDateCalculator(timePeriod));
    uriBuilder.appendQueryParameter("limit", getString(R.string.display_in_view_quantity));
    uriBuilder.appendQueryParameter("minmagnitude", minMagnitude);
    uriBuilder.appendQueryParameter("orderby", orderBy);

    // Hide the empty state View while Loader is running
    mEmptyStateView.setVisibility(View.INVISIBLE);

    // Start Loader and pass in the complete query URL String
    return new EarthquakeLoader(this, uriBuilder.toString());
}

From source file:com.gmail.boiledorange73.ut.map.MapActivityBase.java

/**
 * Restarts.//from w  w  w  .java 2 s.  c o  m
 */
private void restart() {
    // init flag
    this.mLoaded = false;
    this.mStatements.clear();
    // load htmls
    Uri.Builder uriBuilder = (Uri.parse(this.getWebUrl())).buildUpon();
    String url = uriBuilder.toString();
    // loads html (and js)
    this.mWebView.loadUrl(url);
    // registers bridge in JS.
    this.mJSBridge = new JSBridge(this);
    this.mWebView.addJavascriptInterface(this.mJSBridge, "jsBridge");
}

From source file:com.he5ed.lib.cloudprovider.apis.BoxApi.java

/**
 * Search the cloud for all contents/*from  w w  w. j a  va  2 s.c o m*/
 *
 * @param params for search query
 * @param parent folder wto search for
 * @return  list of files and folders that match search criteria
 * @throws RequestFailException
 */
public synchronized List<Object> search(@NonNull Map<String, Object> params, CFolder parent)
        throws RequestFailException {
    List<Object> list = new ArrayList<>();

    Uri uri = Uri.parse(API_BASE_URL);
    Uri.Builder urlBuilder = uri.buildUpon().appendEncodedPath("search");
    // pre-defined parameters
    urlBuilder.appendQueryParameter("limit", "100");
    urlBuilder.appendQueryParameter("scope", "user_content");
    // add the rest of the user defined parameters
    params.put("ancestor_folder_ids", parent.getId());
    for (Map.Entry<String, Object> param : params.entrySet()) {
        urlBuilder.appendQueryParameter(param.getKey(), (String) param.getValue());
    }

    Request request = new Request.Builder().url(urlBuilder.toString())
            .header("Authorization", String.format("Bearer %s", mAccessToken)).get().build();

    try {
        Response response = mHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            JSONObject jsonObject = new JSONObject(response.body().string());
            int total = jsonObject.getInt("total_count");
            // return null if no item found
            if (total == 0)
                return null;

            JSONArray entries = jsonObject.getJSONArray("entries");
            list.addAll(createFilteredItemsList(entries, parent));
            // suspect search result over 100 items
            if (total > 100 && total - list.size() > 0) {
                params.put("offset", "100");
                list.addAll(search(params, parent));
            }
            return list;
        } else {
            throw new RequestFailException(response.message(), response.code());
        }
    } catch (JSONException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    }
}

From source file:com.taobao.weex.WXSDKInstance.java

private String wrapPageName(String pageName, String url) {
    if (TextUtils.equals(pageName, WXPerformance.DEFAULT)) {
        pageName = url;/*  ww w.java  2s.c  o  m*/
        WXExceptionUtils.degradeUrl = pageName;
        try {
            Uri uri = Uri.parse(url);
            if (uri != null) {
                Uri.Builder builder = new Uri.Builder();
                builder.scheme(uri.getScheme());
                builder.authority(uri.getAuthority());
                builder.path(uri.getPath());
                pageName = builder.toString();
            }
        } catch (Exception e) {
        }
    }
    return pageName;
}

From source file:com.facebook.GraphRequest.java

private String appendParametersToBaseUrl(String baseUrl) {
    Uri.Builder uriBuilder = new Uri.Builder().encodedPath(baseUrl);

    Set<String> keys = this.parameters.keySet();
    for (String key : keys) {
        Object value = this.parameters.get(key);

        if (value == null) {
            value = "";
        }/*w ww  . jav a2s. c  o  m*/

        if (isSupportedParameterType(value)) {
            value = parameterToString(value);
        } else {
            if (httpMethod == HttpMethod.GET) {
                throw new IllegalArgumentException(String.format(Locale.US,
                        "Unsupported parameter type for GET request: %s", value.getClass().getSimpleName()));
            }
            continue;
        }

        uriBuilder.appendQueryParameter(key, value.toString());
    }

    return uriBuilder.toString();
}

From source file:com.facebook.Request.java

private String appendParametersToBaseUrl(String baseUrl) {
    Uri.Builder uriBuilder = new Uri.Builder().encodedPath(baseUrl);

    Set<String> keys = this.parameters.keySet();
    for (String key : keys) {
        Object value = this.parameters.get(key);

        if (value == null) {
            value = "";
        }//  w ww .  ja  va 2  s . c o  m

        if (isSupportedParameterType(value)) {
            value = parameterToString(value);
        } else {
            if (httpMethod == HttpMethod.GET) {
                throw new IllegalArgumentException(String.format(
                        "Unsupported parameter type for GET request: %s", value.getClass().getSimpleName()));
            }
            continue;
        }

        uriBuilder.appendQueryParameter(key, value.toString());
    }

    return uriBuilder.toString();
}