url图像下载总是返回空值

gev0vcfq  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(351)

我做错什么了?我得到200 ok的响应,但是图像位图是 null . 我用 Asynctask 检索url图像。我正在尝试将位图分配给imageview。
有什么想法吗?

private class loadMoreListView extends AsyncTask< Void, Void, String> {

        protected String doInBackground(Void... unused) {
            loadingMore = true;

                Bitmap mIcon11 = null;

                try {
                    URL url1 = new URL("https://imgaz2.staticbg.com/thumb/view/oaupload/ser1/banggood/images/E4/21/c5424852-82af-47a1-8a13-54da3d1bc049.jpg");
                    HttpURLConnection connection  = (HttpURLConnection) url1.openConnection();
                    connection.setReadTimeout(10000);
                    connection.setConnectTimeout(10000);
                    connection.setDoInput(true);
                    connection.setRequestMethod("GET");
                    connection.setUseCaches(false);
                    connection.setAllowUserInteraction(false);
                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

                    int responceCode = connection.getResponseCode();
                    Log.i("response_line", Integer.toString(responceCode));
                    InputStream isstream =null;
                    isstream=connection.getInputStream();

                 //inputstream named isstream returns null
                    mIcon11 = BitmapFactory.decodeStream(isstream);
                } catch (Exception e) {
                    Log.e("Error", e.getMessage());
                    e.printStackTrace();
                }

            return result;
        }
slsn1g29

slsn1g291#

看看毕加索/毕加索github。
它允许你在几行代码中做你想做的事情(注意,在android28+httpurl上,除非你做一些额外的工作,否则是不可能的):

Picasso.get().load("https://i.imgur.com/DvpvklR.png").into(imageView);

它处理图像、线程、占位符、转换等的下载、内存或磁盘缓存和回收。不需要重新发明轮子。你甚至可以调整图像大小,并有各种裁剪选项

Picasso.get()
  .load(url)
  .resize(50, 50)
  .centerCrop()
  .into(imageView)

更新:
正如其他人提到的,你不应该使用 AsyncTask 因为它被弃用了。有许多其他库可以用来以线程化和更可读的方式(如volley)发出网络请求。这可以与毕加索配合使用,达到你想要的效果。
下面是一个从google加载一些文本以及加载文本后的图像的示例:

内部版本.gradle:

dependencies {
    ...
    implementation 'com.android.volley:volley:1.1.1'
    implementation 'com.squareup.picasso:picasso:2.71828'
}

androidmanifest.xml:

<uses-permission android:name="android.permission.INTERNET" />

fragment\u first.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".FirstFragment">

    <ImageView
        android:id="@+id/imageview"
        android:layout_width="200dp"
        android:layout_height="200dp"
        app:layout_constraintBottom_toTopOf="@id/textview"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_first_fragment"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/textview"/>

</androidx.constraintlayout.widget.ConstraintLayout>

firstfragment.java文件:

package com.example.myapplication;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.squareup.picasso.Picasso;

public class FirstFragment extends Fragment {

    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_first, container, false);
    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        TextView textView = view.findViewById(R.id.textview);
        ImageView imageView = view.findViewById(R.id.imageview);

        RequestQueue queue = Volley.newRequestQueue(getActivity());
        String url = "https://www.google.com";

        // 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) {
                        // Display the first 500 characters of the response string.
                        textView.setText("Response is: " + response.substring(0, 500));
                        Picasso.get().load("https://i.imgur.com/DvpvklR.png").into(imageView);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                textView.setText("That didn't work!");
            }
        });

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

相关问题