ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

HttpURLConnection 下载图片

2021-05-27 23:05:53  阅读:248  来源: 互联网

标签:HttpURLConnection conn new msg import android Message 下载 图片


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();
                }
            }
        }

    }
}

 

标签:HttpURLConnection,conn,new,msg,import,android,Message,下载,图片
来源: https://blog.csdn.net/a451319296/article/details/117339844

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有