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_http1;

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

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Debug;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.util.logging.LogRecord;

public class MainActivity extends AppCompatActivity {

    final int REQ_SUCCESS=1;
    final  int REQ_ERROR=2;
    private  String path;
    private EditText inputText;
    private TextView textView;

    @SuppressLint("HandlerLeak")
     Handler handler =new Handler(){

         @Override
         public void handleMessage(@NonNull Message msg) {

            switch (msg.what) {
                case REQ_SUCCESS:
                    String text = (String) msg.obj;
                    textView.setText(text);
                    break;

                case REQ_ERROR:
                    Toast.makeText(MainActivity.this,"连接网络失败!",Toast.LENGTH_LONG).show();
                    break;
            }

         }
     };

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

        inputText=findViewById(R.id.editTextTextPersonName);
        textView=findViewById(R.id.textView2);
    }

    public void onClickButton(View view) {

        path=inputText.getText().toString();
        textView.setText(null);

        new Thread() {
            @Override
            public void run() {
                helloHttp();
            }
        }.start();
    }

    public void helloHttp()  {

        BufferedReader reader=null;
        HttpURLConnection conn=null;

        try {

            URL url =new URL(path);
            conn =(HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            conn.connect();//发起连接
            int code=conn.getResponseCode();//200表示连接成功

            System.out.println("Code:"+code);

            if (code==200)
            {
                InputStream inputStream=conn.getInputStream();
                reader=new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder result=new StringBuilder();
                String line;
                while ((line=reader.readLine())!=null)
                {
                    result.append(line);
                }
                System.out.println("连接网络成功!");

                Message msg=new Message();
                msg.what=REQ_SUCCESS;
                msg.obj=result.toString();
                handler.sendMessage(msg);
            }
            else
            {
                Message msg=new Message();
                msg.what=REQ_ERROR;
                msg.obj="连接网络失败!";
                handler.sendMessage(msg);
                System.out.println("连接网络失败!");
            }

        } catch (Exception e) {
            System.out.println("Exception:"+e);
            Message msg=new Message();
            msg.what=REQ_ERROR;
            msg.obj="连接网络失败!";
            handler.sendMessage(msg);
            System.out.println("连接网络失败!");
            e.printStackTrace();
        }

        finally {

            if (conn != null) conn.disconnect();
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

 

上一篇:java IO流从网页链接直接写入文件,无需本地转存


下一篇:UrlConnection