【问题标题】:I am trying to get youtube title from url using json file but i do not get any result and i also do not get any exception我正在尝试使用 json 文件从 url 获取 youtube 标题,但我没有得到任何结果,我也没有得到任何异常
【发布时间】:2021-03-06 06:11:40
【问题描述】:

我正在尝试使用 json 文件从 url 获取 youtube 标题,但我没有得到任何结果,我也没有得到任何异常。我尝试在吐司消息中吐司异常为空/空白。任何人都可以帮助我。我的代码在这里...

String link = youtube url;
URL embededURL = null;
try {
    embededURL = new URL("http://www.youtube.com/oembed?url=" + link + "&format=json");
} catch (MalformedURLException e) {
    e.printStackTrace();
    makeToast(e.getMessage());
}
try {
    title = new JSONObject(IOUtils.toString(embededURL)).getString("title");
} catch (JSONException e) {
    e.printStackTrace();
    makeToast(e.getMessage());
} catch (IOException e) {
    e.printStackTrace();
    makeToast(e.getMessage());
}

makeToast(title);

【问题讨论】:

标签: java apache-commons-io


【解决方案1】:

首先,既然你的问题标签是android-volley,我会给你一个android-volley 的答案。但是,有很多库可以像 OkHttp 这样主观上更好地管理 HTTP 调用。

现在,您的问题的简短回答是您的代码甚至没有拨打互联网电话。

更长的答案:

  1. volley dependency 添加到您的build.gradle
dependencies {
    //... other dependencies
    implementation 'com.android.volley:volley:1.1.1'
}
  1. <uses-permission android:name="android.permission.INTERNET" /> 放入你的AndroidManifest.xml

  2. 让应用程序调用互联网,如下所示。我调整了the Android Volley simple example.

RequestQueue queue = Volley.newRequestQueue(context);
// sample of a URL-encoded url param, so you'll need to convert your link variable if you haven't already
String url = "https://www.youtube.com/oembed?url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DiwGFalTRHDA&format=json";

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
    new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                String title = new JSONObject(response).getString("title");
                Toast.makeText(context, title, Toast.LENGTH_LONG).show();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(context, "Error!", Toast.LENGTH_LONG).show();
        }
    });

// Add the request to the RequestQueue.
queue.add(stringRequest);

【讨论】:

  • 嗨,兄弟,我已经使用了这个,但是如果我们像 e.getMessage 这样的错误,那么它仍然是空白的。我该如何解决这个问题
  • 我的建议是不要使用 toast 来显示错误消息。如果您正在追求 Android 开发,无论是作为爱好还是职业,都可以轻松阅读日志。 Toast 一些用户友好的东西,即使它只是说“发生错误”。
  • 我在我的示例上发布了工作代码,包括示例 URL。您只需将其粘贴到您的非工作代码上,我保证它会为标题敬酒。之后,您必须对其进行调整以满足您的需求。
猜你喜欢
  • 2023-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多