gpt4 book ai didi

java - Uri.Builder 以满足 Google 图书要求

转载 作者:行者123 更新时间:2023-12-01 23:19:56 24 4
gpt4 key购买 nike

我正在尝试使用 Uri.Builder 按照 Google Books API 的请求创建兼容的网址。 (而不是连接字符串)这是我需要创建的 URL:

获取 https://www.googleapis.com/books/v1/volumes?q=green+flowers+inauthor:brown&key=yourAPIKey

第一部分是传递包含空格的搜索查询:green+flowers

在此之后我需要添加一个特殊请求:特殊关键字是“inauthor”。正如您所看到的,第一个和第二个查询必须使用加号“+”连接起来。我还需要使用这个“:”连接到我的第二个查询“brown”

但是我的代码:

        Uri.Builder uriBuilder = new Uri.Builder();
uriBuilder.scheme("https")
.authority("www.googleapis.com")
.appendPath("books").appendPath("v1").appendPath("volumes")
.appendQueryParameter("q", primaryQuery);
//Search Mode
switch (sharedPreferences.readSharedPreferencesInt(this.getBaseContext(), "searchMode", 0)) {
case 0: //Google default
//doNothing
break;
case 1: //byTitle
uriBuilder.appendQueryParameter("intitle", secondaryQuery);
break;
case 2: //byAuthor
uriBuilder.appendQueryParameter("inauthor", secondaryQuery);
break;
case 3: //byPublisher
uriBuilder.appendQueryParameter("inpublisher", secondaryQuery);
uriBuilder.
break;
case 4://bySubject
uriBuilder.appendQueryParameter("subject", secondaryQuery);
break;
case 5: //byISBN
uriBuilder.appendQueryParameter("isbn", secondaryQuery);
break;
case 6: //byLCCN
uriBuilder.appendQueryParameter("lccn", secondaryQuery);
break;
case 7: //byOCLC
uriBuilder.appendQueryParameter("oclc", secondaryQuery);
break;
}

uriBuilder.appendQueryParameter("maxResults", String.valueOf((sharedPreferences.readSharedPreferencesInt(this.getBaseContext(), "maxResults", 10) + 10)));//Default for maxResults is 10 but we choose 20

产生此结果(主要查询“harry potter”和次要查询“rowling”):

https://www.googleapis.com/books/v1/volumes?q=Harry%20potter&inauthor=rowling&maxResults=10&orderBy=relevance&printType=books

我尝试使用 AppendEncodedPath 函数,但它也产生了一个不需要的“?”到字符串末尾。

最佳答案

我找到了一个简单的解决方法:在创建 url 并应用我的需求之前拦截 uri.builder:

        String url = uriBuilder.toString();
url = url.replace("%20%20%20", "+");
url = url.replace("%20%20", "+");
url = url.replace("%20", "+");
url = url.replace("&intitle=", "+intitle:");
url = url.replace("&inauthor=", "+inauthor:");
url = url.replace("&inpublisher=", "+inpublisher:");
url = url.replace("&subject=", "+subject:");
url = url.replace("&isbn=", "+isbn:");
url = url.replace("&lccn=", "+lccn:");
url = url.replace("&oclc=", "+oclc:");

//return createUrl(uriBuilder.toString());
return createUrl(url);
}

private static URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error creating URL ", e);
}
return url;
}

请注意:Google 图书搜索现在按预期工作,我使用了以下代码:

        url = url.replace("%20%20%20", "+");
url = url.replace("%20%20", "+");
url = url.replace("%20", "+");

防止关键字之间有两个或三个空格。希望这对其他人有帮助。

关于java - Uri.Builder 以满足 Google 图书要求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58331524/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com