Android access to network resources

Android access to network resources

When we write an Android APP, we must consider a very important question, that is, how to make the APP call other resources on the Internet? At this time, you need to use URL (Uniform Resource Locator).

URL stands for Uniform Resource Locator, which is a pointer to a "resource" on the Internet. The so-called resources can be simple files or directories, or references to more complex objects, such as queries to databases, search engines, and so on. Generally speaking, URL can be composed of protocol name, host, port and resource, the following format is as follows:

	protocol://host:port/resource

The URL class provides multiple constructors for creating URL objects. Once the URL object is obtained, the following common methods can be called to access the resources corresponding to the URL.

->String getFile():获取此URL的资源名;
->String getHost():获取此URL的主机名;
->String getPath():获取此URL的路径部分;
->String getPort():获取此URL的端口号;
->String getProtocol():获取此URL的协议名称;
->String getQuery():获取此URL的查询字符串部分;
->URLConnection openConnection():返回一个URLConnection对象,它表示到URL所引用的远程对象的连接;
InputStream openStream():打开与此URL的连接,并返回一个用于读取该URL资源的InputStream

example,

Network permissions
First of all, we need to know that connecting to network resources definitely requires access to the Internet, which involves the issue of network permissions. This requires us to add the following authorization code in AndroidManifest.xml:

<!--授权网络权限-->
<user-permission android:name="android.permission.INTERNET"/>

Layout file and Java part
Let's modify the layout in activity_main.xml first

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">
 
    <TextView
        android:id="@+id/tv_show"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        />
 
    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="@string/app_name" />
</RelativeLayout>

Then we write down the method of calling the interface in MainActivity.java, and display it in the text box

package com.example.ajoke;
 
import androidx.appcompat.app.AppCompatActivity;
 
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
 
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
 
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    
    
 
    private TextView mTvShow;
    private HttpURLConnection connection;
    private InputStream inputStream;
    private BufferedReader bufferedReader;
    private final int GET_DATA_SUCCESS = 101;//获取成功的标志
 
    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler(new Handler.Callback() {
    
    
        public boolean handleMessage(Message msg){
    
    
            if (msg.what==GET_DATA_SUCCESS){
    
    
                String data = msg.getData().getString("data");
                mTvShow.setText(data);
            }
            return false;
        }
    });
 
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        //初始化控件
        initUI();
 
        //初始化数据
        initData();
 
    }
 
    private void initUI() {
    
    
        //获取文本框
        mTvShow = findViewById(R.id.tv_show);
        //获取按钮并绑定监听事件
        findViewById(R.id.btn).setOnClickListener(this);
 
    }
 
 
    @Override
    public void onClick(View v) {
    
    
        initData();
    }
    //初始化数据
    private void initData() {
    
    
        new Thread(new Runnable() {
    
    
            @Override
            public void run() {
    
    
                String data = getDataFromServer();
 
                //创建信息对象
                Message message = Message.obtain();
                Bundle bundle = new Bundle();
                bundle.putString("data",data);
                message.setData(bundle);
                message.what = GET_DATA_SUCCESS;
                //向主线程发信息
                mHandler.sendMessage(message);
            }
        }).start();
    }
 
    //从服务器获取数据
    private String getDataFromServer() {
    
    
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        try {
    
    
            //创建URL
            URL url = new URL("https://autumnfish.cn/api/joke");
 
            //打开连接
                connection = (HttpURLConnection) url.openConnection();
 
            //判断并处理结果
                //请求网络状态码200为正常
            if (connection.getResponseCode()==200){
    
    
                //获取输入流
                inputStream = connection.getInputStream();
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
 
                StringBuilder stringBuilder = new StringBuilder();
                for (String line = "";(line = bufferedReader.readLine())!=null;){
    
    
                    stringBuilder.append(line);
                }
 
                return stringBuilder.toString();
            }
 
        }catch (Exception e){
    
    
            e.printStackTrace();
        }finally {
    
    
            try {
    
    
                if (bufferedReader!=null)bufferedReader.close();
                if (inputStream!=null)inputStream.close();
                if (connection!=null)connection.disconnect();
            }catch (Exception e){
    
    
                e.printStackTrace();
            }
        }
 
        return "";
    }
}

Result
The following is the effect of the code
insert image description here

Lin Zebin
Original link: https://blog.csdn.net/m0_71507626/article/details/128174851

Guess you like

Origin blog.csdn.net/fjnu_se/article/details/128179757