Romulus Urakagi Ts'ai Romulus Urakagi Ts'ai - 1 month ago 18
Android Question

How to put API key into Youtube.Builder in Youtube's Android API?

I am trying to retrieve a Youtube Channel in an Android app, and has below code:

HttpTransport transport = new NetHttpTransport();
JsonFactory jsonFactory = new GsonFactory();
GoogleCredential credential = new GoogleCredential()
.setAccessToken("<my api key>");
YouTube yt = new YouTube.Builder(transport, jsonFactory,
credential).build();
try {
List l = yt.channels().list("id");
l.put("id", "UCO3bfz4KY6zGT5IOaFJuxpA");
ChannelListResponse resp = l.execute();
java.util.List<Channel> chs = resp.getItems();
for (Channel ch : chs) {
// ...
}
} catch (IOException e1) {
e1.printStackTrace();
}


But I got error response message
"Invalid Credentials"
. I am using the API key in
https://console.developers.google.com/project/<project name>/apiui/credential
, segmentation of
Public API access
,
API KEY
.

I am not sure I'm using wrong key, wrong API, setting up wrong, should not run with debug key, or something other wrong. Can anyone help? Thanks!

Answer

I found the method is in the List.

List l = yt.channels().list("id");
l.setKey("<Browser API Key");  // This line
l.put("id", "UCO3bfz4KY6zGT5IOaFJuxpA");

Note that don't use Android API Key here since it's for Player API, not Data API. I need to create a new browser key with empty refer limitation to make things work.

See a full Java code example on Google's YouTube > Data API website using setKey():
https://developers.google.com/youtube/v3/docs/videos/list#examples