Building URL- Confusion on a couple of lines

泪湿孤枕 提交于 2019-12-24 06:35:12

问题


I am trying to understand this class/method involved in a Udacity Android Development course, and I am confused on a couple lines. I was wondering how the String Param_QUERY = "q" works, and looking for any explanation. In addition, I was also confused about PARAM_SORT, and sortBy. Any explanation on these three variables and how they are used would be much appreciated. Thanks, and sorry for any strange formatting.

public class NetworkUtils {

     final static String GITHUB_BASE_URL =
             "https://api.github.com/search/repositories";

     final static String PARAM_QUERY = "q";

     final static String PARAM_SORT = "sort";
     final static String sortBy = "stars";

/**
 * Builds the URL used to query Github.
 *
 * @param githubSearchQuery The keyword that will be queried for.
 * @return The URL to use to query the weather server.
 */
public static URL buildUrl(String githubSearchQuery) {

    Uri builtUri = Uri.parse(GITHUB_BASE_URL).buildUpon()
            .appendQueryParameter(PARAM_QUERY, githubSearchQuery)
            .appendQueryParameter(PARAM_SORT, sortBy)
            .build();

    URL url = null;
    try {
        url = new URL(builtUri.toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    return url;
}

回答1:


This isn't really an Android issue, but I'll explain what is going on. First, what the code is doing is building a string like:

https://api.github.com/search/repositories?q=githubSearchQuery&sort=stars

This is a REST endpoint, and when you query that page on GitHub, it searches repositories, with the search string passed through q=githubSearchQuery, replaced with of course your input, and sorts the results according to sort=stars, sorting by the number of stars. Now, the Java part works as follows:

appendQueryParameter(PARAM_SORT, sortBy)

For the simple case, with constant strings, this specifies the sort=stars part, plus adds any required & to chain with other parameters.

appendQueryParameter(PARAM_QUERY, githubSearchQuery)

This is similar for the q=githubSearchQuery, but since this is user input, there may be spaces or other special characters in the string, so appendQueryParameter() also mangles your string into valid HTML query parameters. So, if I search for & = /?, I get the query parameter q=%26+%3D+%2F%3F.

By the way, the q= part is not a standard, just a convention for queries (Google uses that too), and sort=stars is an option specific to GitHub.




回答2:


it will make your url looks like this, the appendQueryParameter will add used params inside the url

https://api.github.com/search/repositories?q=githubSearchQueryValue&sort=stars


来源:https://stackoverflow.com/questions/44937224/building-url-confusion-on-a-couple-of-lines

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!