尝试使用 glide 和 volley 从 URL 获取图像,onResponse 方法出错

Trying to use glide and volley to get an image from a URL, getting an error onResponse method

代码如下,它给我一个 onResponse 方法的错误:

RequestQueue queue = Volley.newRequestQueue(this);
// Url for the API call
String url = "https://meme-api.herokuapp.com/gimme";

// Request a string response from the provided URL.
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject response) {

        String url = response.toString();

        ImageView imageView = (ImageView) findViewById(R.id.MemeImageView);

        Glide.with(this).load(url).into(imageView);
    }
}, new Response.ErrorListener()

您应该首先检查您的请求的响应。

这里是:

您正在将整个响应转换为字符串并在 Glide 中将其作为 URL 传递。但您只需要此回复中的图像 URL。

所以你的图片URL应该是这样的:

String url = response.getString("url");

您可以在不将其保存到新字符串中的情况下执行此操作。只需首先检查响应是否为 null 以及响应是否包含“url”属性,然后在您的案例中直接在 imageview 中使用 response.getString("url")。

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
        (Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
             if(response!=null && response.getString("url")!null){
Glide.with(this).load(response.getString("url")).into(findViewById(R.id.MemeImageView));
}
            }
        }, new Response.ErrorListener() ....