我正在尝试开发我的应用程序的一部分,我想在其中获取关键字的视频详细信息。我正在使用搜索列表API。我想我的授权问题。我得到了401.我试过传递我的授权细节。
我在网上浏览了一些资源之后尝试了以下代码,我当前在获取输入流的行中获取了java.io.FileNotFoundException。我得到的连接代码是401。
给定的代码位于AsyncTask的doInBackground中。
String ytres="";
URL url;
HttpURLConnection urlConnection = null;
try {
Log.d("youtubedata","a1");
url = new URL("https://www.googleapis.com/youtube/v3/search?part=id&q=queen%20bohemian");
Log.d("youtubedata","a2");
Log.d("youtubedata","a");
urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty ("Authorization", "Bearer MYAPIKEY");
urlConnection.setRequestProperty ("Accept", "application/json");
Log.d("youtubedatanum",Integer.toString(urlConnection.getResponseCode()));
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
ytres=ytres+current;
System.out.print(current);
}
Log.d("youtubedata",ytres);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return ytres;
我怀疑问题是我通过API密钥的方式。
请浏览Calling the API和Search Endpoint上的API文档。
您将看到您的URL不包含作为关键参数传递的所需API密钥。
在Search.java上挖掘谷歌自己的Java实现样本也是值得的。但是,该代码由于它使用的图层抽象层而不是直接的帮助,因为它模糊了客户端应该直接使用API的方式。