day13:HttpURLConnection網(wǎng)絡(luò)請求,讀取網(wǎng)上圖片

HttpURLConnection繼承了URLConnection,是一個輕量級的網(wǎng)絡(luò)請求,是抽象類,無法直接實例化對象。

首先介紹他的使用方法:

1、建立url對象:
URL url = new URL();
2、獲取URL實例:
HttpURLConnection huc = (HttpURLConnection)url.openConnection();
3、設(shè)置獲取方法:
huc.RequestMethod("GET");或者POST
4、設(shè)置響應(yīng)時間:
huc.setConnectionTimeout(101000);huc.setReadTimeout(101000);
5、返回輸入流,然后讀取:
InputStream in = huc.getInputStream();
6、關(guān)閉網(wǎng)絡(luò)請求:
huc.disconnect();

注意:這個小例子 要明白幾個知識點:

1、因為是請求網(wǎng)上的圖片加載,所以耗時間,因此要放在子線程中。
2、子線程不能更新UI,所以要用handler來更新UI;
3、handler的用法:
創(chuàng)建一個handler對象
private Handler handler = new Handler();
重寫handlerMessage方法
public void handlerMessage(android.os.Message msg){
}
在子線程中創(chuàng)建Message對象,將數(shù)據(jù)綁定個msg。
Message msg = new Message();
msg.obj = result;
子線程的message對象msg將在子線程中使用senMessage()發(fā)個主線程的handler
handler.senMessage(msg);
主線程的handlermessage的方法接受子線程的數(shù)據(jù),就可以更新UI了;

先看一下效果圖:
1526311964223.gif
第一步還是先看主xml文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edit"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="查看圖片"
        android:id="@+id/button"/>
    <ScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <ImageView
            android:id="@+id/image"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </ScrollView>

</LinearLayout>

<ScrollView>這個是滾動條,就是如果圖片很大就可以滾動著看(有點表達(dá)不清楚);

接著看主activity:

現(xiàn)在我比較喜歡在代碼上注釋,因為這樣可以更清晰,而且自己也會在理一遍思路(畢竟是初學(xué)者):

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
//我們設(shè)置點擊事件,所以要繼承OnClickListener接口
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
//初始化對象
    private EditText editText;
    private ImageView imageView;
    private Context mContext;//這個Context很強大,代表著...,總之寫這個會讓后面的代碼簡潔一點
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
//通過ID找到xml的控件
        editText = (EditText) findViewById(R.id.edit);
        Button button = (Button) findViewById(R.id.button);
        imageView = (ImageView) findViewById(R.id.image);
//為bottom注冊點擊監(jiān)聽
        button.setOnClickListener(this);
    }
//這個是handler的步驟
    private Handler handler = new Handler(){
        public void handleMessage(android.os.Message msg){
            Bitmap bitmap = (Bitmap) msg.obj;
            imageView.setImageBitmap(bitmap);
        };
    };

    @SuppressLint("WrongConstant")
    @Override
    public void onClick(View v) {
        try{
//得到EditText的里面的內(nèi)容
            final String url = editText.getText().toString().trim();
//判斷URL填寫的是否為空
            if(TextUtils.isEmpty(url)){
                Toast.makeText(mContext,"url不能為空",0).show();
                return;
            }
//創(chuàng)建一個子線程,重寫run方法
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
//這個是網(wǎng)絡(luò)請求,把它放在子線程里
                        URL url1 = new URL(url);
                        HttpURLConnection connection=(HttpURLConnection)url1.openConnection();
                        connection.setRequestMethod("GET");
                        connection.setConnectTimeout(1000*10);
//獲取請求數(shù)據(jù)響應(yīng)碼
                        int code = connection.getResponseCode();
//如果code==200代表請求成功
                        if(code == 200){
//獲取輸入流,并轉(zhuǎn)換成String
                            InputStream inputStream = connection.getInputStream();
//把輸入流轉(zhuǎn)化成圖片
                            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                            Message msg = Message.obtain();
                            msg.obj = bitmap;
                            handler.sendMessage(msg);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }).start();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
創(chuàng)建一個獲取文件的流并轉(zhuǎn)換成String的工具類
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

public class StreamUtils {


    public static String streamToString(InputStream  in){
        String result ="";

        try{
            //創(chuàng)建一個字節(jié)數(shù)組寫入流
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            
            byte[] buffer = new byte[1024];
            int length = 0;
            while (  (length =  in.read(buffer)) !=-1) {
                out.write(buffer, 0, length);
                out.flush();
            }
            
            result = out.toString();//將字節(jié)流轉(zhuǎn)換成string
            
            out.close();
        }catch (Exception e) {
            e.printStackTrace();
        }


        return result;
    }
}
最后:

封裝 GDI+ 位圖,此位圖由圖形圖像及其屬性的像素數(shù)據(jù)組成。Bitmap 是用于處理由像素數(shù)據(jù)定義的圖像的對象。
還有增加訪問Internet權(quán)限:
android.permission.INTERNET

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1.寫一個網(wǎng)絡(luò)源碼查看器 思路: 1.寫布局 EditText Button TextView ok 2.找控件,...
    123yuan123閱讀 393評論 0 1
  • 前言 在Android開發(fā)的多線程應(yīng)用場景中,Handler機制十分常用 今天,我將手把手帶你深入分析Handle...
    BrotherChen閱讀 530評論 0 0
  • 談到Android開發(fā),就離不開線程操作,而我們需要在子線程中更新UI,一般有以下幾種方式: 1、view.pos...
    StChris閱讀 1,419評論 0 1
  • 你看下上海35歲外來人的生活狀態(tài),當(dāng)然了各有各的不同,可比性不大 那些不聽話,不打招呼的,不怕的,可能更有骨氣,能...
    三不主義閱讀 163評論 0 0
  • 這美輪美奐的風(fēng)景是不是有種巴比倫空中花園的錯覺? 這里就是美麗的西班牙故宮,阿爾漢布拉宮。 今天我們的主角就是阿爾...
    米寶星球閱讀 1,367評論 2 7

友情鏈接更多精彩內(nèi)容