gpt4 book ai didi

android - Youtube API key

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:07:15 27 4
gpt4 key购买 nike

当我尝试使用 YouTube API 进行搜索时,出现此错误:

There was a service error: 403 : The request did not specify any Android package name or signing-certificate fingerprint. Please ensure that the client is sending them or use the API Console to update your key restrictions.

在 MainActivity 中我有这段代码:

youtube = new YouTube.Builder(new NetHttpTransport(), JSON_FACTORY, new HttpRequestInitializer() {
@Override
public void initialize(HttpRequest httpRequest) throws IOException {

}
}).setYouTubeRequestInitializer(new YouTubeRequestInitializer(apiKey)).setApplicationName("Some Name").build();

在云控制台中,我有一个适用于 Android 的 ApiKey,其中设置了包名称和使用 keytool 命令获取的 SHA-1 编号。

最佳答案

最后我找到了解决这个问题的办法:)

在 Google Developer Console 中创建 API_KEY 并使用“包名称”和“SHA-1 证书指纹”对其进行限制后,您必须在每个 youtube api 请求中提供这些数据。以下步骤:

1- 获取包名:

String packageName = context.getPackageName();

2- 获取 SHA-1:

private String getSHA1(String packageName){
try {
Signature[] signatures = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES).signatures;
for (Signature signature: signatures) {
MessageDigest md;
md = MessageDigest.getInstance("SHA-1");
md.update(signature.toByteArray());
return BaseEncoding.base16().encode(md.digest());
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}

3- 准备 youtube api http header :

youTube = new YouTube.Builder(new NetHttpTransport(), JacksonFactory.getDefaultInstance(), new HttpRequestInitializer() {
@Override
public void initialize(HttpRequest request) throws IOException {
String packageName = context.getPackageName();
String SHA1 = getSHA1(packageName);

request.getHeaders().set("X-Android-Package", packageName);
request.getHeaders().set("X-Android-Cert",SHA1);
}
}).setApplicationName(appName).build();

4- 根据需要构建您的 youtube api 查询:例如搜索视频:

YouTube.Search.List query;
query = youTube.search().list("id, snippet");
query.setKey(YOUR_API_KEY);
query.setType("video");
query.setFields("items(id/videoId,snippet/title,snippet/description,snippet/thumbnails/default/url)");
query.setQ(search keywords);
SearchListResponse response = query.execute();
List<SearchResult> results = response.getItems();

然后处理返回的搜索结果。

关于android - Youtube API key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39543105/

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