最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Android入門(mén)之使用OKHttp組件訪問(wèn)網(wǎng)絡(luò)資源

 更新時(shí)間:2022年12月26日 16:23:42   作者:TGITCIC  
這篇文章主要為大家詳細(xì)介紹了Android如何使用OKHttp組件訪問(wèn)網(wǎng)絡(luò)資源功能,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,需要的可以參考一下

簡(jiǎn)介

今天的課程開(kāi)始進(jìn)入高級(jí)課程類了,我們要開(kāi)始接觸網(wǎng)絡(luò)協(xié)議、設(shè)備等領(lǐng)域編程了。在今天的課程里我們會(huì)使用OKHttp組件來(lái)訪問(wèn)網(wǎng)絡(luò)資源而不是使用Android自帶的URLConnection。一個(gè)是OKHttp組件更方便二個(gè)是OKHttp組件本身就帶有異步回調(diào)功能。

下面就進(jìn)入課程。

課程目標(biāo)

我們的課程目標(biāo)有4個(gè)點(diǎn):

  • 使用OKHttp組件;
  • 使用OKHttp組件加載網(wǎng)絡(luò)圖片顯示在APP的ImgView里;
  • 使用OKHttp組件加載給定網(wǎng)頁(yè)代碼顯示在ScrollView里;
  • 使用OKHttp組件加載給定網(wǎng)頁(yè)顯示在WebView里;

以上過(guò)程都為異步加載。

代碼前在gradle里要先聲明對(duì)于OKHttp組件的引用

要使用OKHttp組件,我們必須要在build.gradle中加入以下語(yǔ)句:

implementation 'com.squareup.okhttp3:okhttp:3.10.0'

以下是加完上述語(yǔ)句后的build.gradle。

訪問(wèn)網(wǎng)絡(luò)資源需要給到APP以權(quán)限

我們因?yàn)橐L問(wèn)網(wǎng)絡(luò)資源,因此我們需要給到APP以相應(yīng)的權(quán)限。編輯AndroidManifest.xml文件,并加入以下兩行聲明。

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

加完后的AndroidManifest.xml長(zhǎng)這樣

代碼

菜單res\menu\pop_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menuItemDisplayPic" android:title="加載圖片" />
    <item android:id="@+id/menuItemDisplayHtmlCode" android:title="加載網(wǎng)頁(yè)代碼" />
    <item android:id="@+id/menuItemDisplayHtmlPage" android:title="加載網(wǎng)頁(yè)" />
</menu>

主UI界面

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
 
    <Button
        android:id="@+id/buttonShowMenu"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textColor"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:text="展示彈出菜單" />
 
    <ImageView
        android:id="@+id/imgPic"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="gone" />
 
    <ScrollView
        android:id="@+id/scroll"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="gone">
 
        <TextView
            android:id="@+id/htmlTxt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </ScrollView>
    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
 
</LinearLayout>

MainActivity

package org.mk.android.demo.http;
 
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.Log;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.ScrollView;
import android.widget.TextView;
 
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import okhttp3.OkHttpClient;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
public class MainActivity extends AppCompatActivity {
 
    private String TAG = "DemoOkHttp";
    private Button buttonShowMenu;
    private TextView htmlTxt;
    private ImageView imgPic;
    private WebView webView;
    private ScrollView scroll;
    private Bitmap bitmap;
    private String htmlContents;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        buttonShowMenu = (Button) findViewById(R.id.buttonShowMenu);
        htmlTxt = (TextView) findViewById(R.id.htmlTxt);
        imgPic = (ImageView) findViewById(R.id.imgPic);
        webView = (WebView) findViewById(R.id.webView);
        scroll = (ScrollView) findViewById(R.id.scroll);
        buttonShowMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PopupMenu popup = new PopupMenu(MainActivity.this, buttonShowMenu);
                popup.getMenuInflater().inflate(R.menu.pop_menu, popup.getMenu());
                popup.setOnMenuItemClickListener(new MenuItemClick());
                popup.show();
            }
        });
    }
 
    // 定義一個(gè)隱藏所有控件的方法:
    private void hideAllWidget() {
        imgPic.setVisibility(View.GONE);
        scroll.setVisibility(View.GONE);
        webView.setVisibility(View.GONE);
    }
 
    private class MenuItemClick implements PopupMenu.OnMenuItemClickListener {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            String imgPath = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.alicdn.com%2Fi2%2F2542318073%2FO1CN01fJvTi029VTwR16EvP_%21%212542318073.jpg&refer=http%3A%2F%2Fimg.alicdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1673938156&t=69e5ee87fbf4b81b5f6eea53ed5b5158";
            String htmlPagePath = "https://www.baidu.com";
            switch (item.getItemId()) {
                case R.id.menuItemDisplayPic:
                    downLoadImgFromPath(imgPath);
                    break;
                case R.id.menuItemDisplayHtmlCode:
                    getHtmlAsync(htmlPagePath, 102);
                    break;
                case R.id.menuItemDisplayHtmlPage:
                    getHtmlAsync(htmlPagePath, 103);
 
                    break;
            }
            return true;
        }
    }
 
    private Handler httpHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            Log.i(TAG, ">>>>>>receive handler Message msg.what is: " + msg.what);
            switch (msg.what) {
                case 101:
                    hideAllWidget();
                    imgPic.setVisibility(View.VISIBLE);
                    Log.i(TAG, "begin to show img from bitmap type's data");
                    imgPic.setImageBitmap(bitmap);
                    break;
                case 102:
                    hideAllWidget();
                    Log.i(TAG, "begin to show html contents");
                    scroll.setVisibility(View.VISIBLE);
                    Log.d(TAG, ">>>>>>htmlContents->\n" + htmlContents);
                    htmlTxt.setText(htmlContents);
                    break;
                case 103:
                    hideAllWidget();
                    Log.i(TAG, "begin to show html page in webview");
                    webView.setVisibility(View.VISIBLE);
                    Log.d(TAG, ">>>>>>htmlContents->\n" + htmlContents);
                    webView.loadDataWithBaseURL("", htmlContents, "text/html", "UTF-8", "");
                    break;
            }
            return false;
        }
    });
    /**
     * 使用okhttp 異步下載圖片
     */
    private void downLoadImgFromPath(String path) {
 
        OkHttpClient client = new OkHttpClient();
 
        Request request = new Request.Builder()
                .url(path)
                .build();
        Log.i(TAG, ">>>>>>into doanloadImgFromPath method");
        try {
            Call call = client.newCall(request); // 使用client去請(qǐng)求
 
            call.enqueue(new Callback() { // 回調(diào)方法,>>> 可以獲得請(qǐng)求結(jié)果信息
                InputStream inputStream = null;
 
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e(TAG, ">>>>>>下載失敗", e);
                }
 
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    Log.i(TAG, ">>>>>>into onResponse method");
                    try {
                        inputStream = response.body().byteStream();
                        Log.i(TAG, ">>>>>>the response code is: " + response.code());
                        if (200 == response.code()) {
                            bitmap = BitmapFactory.decodeStream(inputStream);
                            Log.i(TAG, ">>>>>>sendEmptyMessage 101 to handler");
                            httpHandler.sendEmptyMessage(101);
                        } else {
                            Log.i(TAG, ">>>>>>下載失敗");
                        }
                    } catch (Exception e) {
                        Log.e(TAG, ">>>>>>okHttp onResponse error: " + e.getMessage(), e);
                    } finally {
                        try {
                            inputStream.close();
                        } catch (Exception e) {
                        }
                    }
                }
            });
 
        } catch (Exception e) {
            Log.e(TAG, ">>>>>>OkHttp調(diào)用失敗", e);
        }
    }
 
    //異步不需要?jiǎng)?chuàng)建線程
    private void getHtmlAsync(String path, int handlerCode) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(path).build();
        //請(qǐng)求的call對(duì)象
        Call call = client.newCall(request);
        //異步請(qǐng)求
        call.enqueue(new Callback() {
 
            //失敗的請(qǐng)求
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e(TAG, ">>>>>>加載path失敗", e);
            }
 
            //結(jié)束的回調(diào)
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                //響應(yīng)碼可能是404也可能是200都會(huì)走這個(gè)方法
                Log.i(TAG, ">>>>>>the response code is: " + response.code());
                if (200 == response.code()) {
                    try {
                        ResponseBody responseBody = response.body();
                        BufferedSource source = responseBody.source();
                        source.request(Long.MAX_VALUE);
                        Buffer buffer = source.buffer();
                        Charset UTF8 = Charset.forName("UTF-8");
                        htmlContents = buffer.clone().readString(UTF8);
                        Log.i(TAG, ">>>>>>sendEmptyMessage " + handlerCode + " to handler");
                        httpHandler.sendEmptyMessage(handlerCode);
                        Log.i(TAG, "getAsyncHtmlGet成功");
                    } catch (Exception e) {
                        Log.e(TAG, ">>>>>>read htmlPage error: " + e.getMessage(), e);
                    }
                }
            }
        });
    }
}

核心代碼導(dǎo)讀

我們使用的是

Call call = client.newCall(request);

它本身就是支持異步的一個(gè)調(diào)用。 然后在得到相應(yīng)的Http報(bào)文后使用一個(gè)Handler向APP主界面發(fā)起改變界面中內(nèi)容的調(diào)用。

這邊有一點(diǎn)需要注意的是OKHttp在返回的response.body()這個(gè)API,在一次請(qǐng)求里只能被使用一次。即如果你已經(jīng)有以下一句類似的調(diào)用:

inputStream = response.body().byteStream();

你就不能再在它以下的語(yǔ)句中調(diào)用一次response.body()了。

自己動(dòng)一下手試試看效果吧。

到此這篇關(guān)于Android入門(mén)之使用OKHttp組件訪問(wèn)網(wǎng)絡(luò)資源的文章就介紹到這了,更多相關(guān)Android OKHttp訪問(wèn)網(wǎng)絡(luò)資源內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

顺义区| 林周县| 三明市| 县级市| 洛浦县| 广水市| 绥德县| 南丹县| 比如县| 清丰县| 平果县| 河源市| 信宜市| 太和县| 黔西| 兴化市| 辽宁省| 榕江县| 鲁山县| 贺州市| 中阳县| 凤翔县| 江都市| 金平| 大名县| 南川市| 鄂尔多斯市| 明星| 怀集县| 通道| 吕梁市| 汝阳县| 桦南县| 丹江口市| 隆德县| 桂阳县| 彰武县| 永安市| 策勒县| 定州市| 榆树市|