public static class GetTitleTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
try {
String youtubeUrl = urls[0];
if (youtubeUrl != null) {
URL url = new URL("http://www.youtube.com/oembed?url=" youtubeUrl "&format=json");
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:221.0) Gecko/20100101 Firefox/31.0");
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.d(TAG, "HTTP response code is " connection.getResponseCode());
return null;
}
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line "\n");
Log.d("Response: ", "> " line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String title) {
Log.v(TAG, "onPostExecute: " title);
super.onPostExecute(title);
// ...
}
}
輸入例如:https ://www.youtube.com/watch?v=hT_nvWreIhg
這總是回傳null。HTTP 回應代碼是403. 這就是為什么我嘗試添加用戶代理,但沒有幫助。
有沒有什么辦法解決這一問題?我想在不使用 YouTube API 的情況下獲取視頻標題。
uj5u.com熱心網友回復:
我嘗試用 curl 獲取它。您的 URL 使用http而不是https://...,將其更改為https://www.youtube.com/oembed?url=。
嘗試在 URL 開頭時獲取 URL 只是http導致我的 403 狀態。但是https成功了。
URL url = new URL("http://www.youtube.com/oembed?url=" youtubeUrl "&format=json");
應改為:
URL url = new URL("https://www.youtube.com/oembed?url=" youtubeUrl "&format=json");
uj5u.com熱心網友回復:
服務器不同意完成請求(錯誤代碼 403)。這可能是由于協議。嘗試使用HttpsURLConnection而不是 HttpURLConnection。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/489974.html
上一篇:在表格的所有列上搜索關鍵字
