HttpURLConnection 下载图片

Posted DaLiangChen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpURLConnection 下载图片相关的知识,希望对你有一定的参考价值。

1.activity_main.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=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="28dp"
        android:layout_marginEnd="16dp"
        android:text="查看"
        android:onClick="onClickButton"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/editTextTextPersonName"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="https://www.baidu.com"
        app:layout_constraintEnd_toStartOf="@+id/button"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/button" />

    <ScrollView
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editTextTextPersonName">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:id="@+id/textView2"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="显示查看的网页内容" />
        </LinearLayout>
    </ScrollView>

</androidx.constraintlayout.widget.ConstraintLayout>

2.MainActivity

package com.daliang.demo_http_image;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class MainActivity extends AppCompatActivity {

    EditText editText;
    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText = findViewById(R.id.editTextTextPersonName);
        imageView = findViewById(R.id.imageView2);
    }

    public void onClickButton(View view) {
        new Thread() {
            @Override
            public void run() {
                getImage();
            }
        }.start();
    }

    private void getImage() {

        String path=editText.getText().toString().trim();
        String pathBase64= Base64.encodeToString(path.getBytes(),Base64.DEFAULT);

        File file =new File(getCacheDir(),pathBase64);

        if (file.exists())
        {
            Bitmap bitmap= BitmapFactory.decodeFile(file.getAbsolutePath());
            runOnUiThread(()-> imageView.setImageBitmap(bitmap) );
            
            return;
        }

        try {
            URL url = null;
            url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            conn.connect();
            int code = conn.getResponseCode();
            System.out.println("code:"+code);
            if (code == 200) {

                InputStream inputStream=conn.getInputStream();

                FileOutputStream outputStream=new FileOutputStream(file);
                int len=-1;
                byte[] buffer=new byte[1024];
                while ((len=inputStream.read(buffer))!=-1)
                {
                    outputStream.write(buffer,0,len);
                }
                outputStream.close();
                inputStream.close();

                Bitmap bitmap= BitmapFactory.decodeFile(file.getAbsolutePath());

                runOnUiThread(()-> imageView.setImageBitmap(bitmap) );

            } else {

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

 

以上是关于HttpURLConnection 下载图片的主要内容,如果未能解决你的问题,请参考以下文章

HttpsURLConnection HttpURLConnection下载图片

HttpURLConnection 下载图片

HttpURLConnection 传输数据和下载图片

Java HttpURLConnection 下载图片 图片全是“加密图片”文字,怎么解决?

HttpURLConnection下载图片的两种方式

httpurlconnection下载pdf文件打不开的原因,和解决代码