Android访问网络资源
当我们写AndroidAPP的时候,一定会考虑一个很重要的问题,那就是如何让APP能调用网上的其他资源呢?这时候就需要用到URL(Uniform Resource Locator)。
URL代表统一资源定位器,它是指向互联网“资源”的指针。所谓的资源,可以是简单的文件或者目录,也可以是更复杂的对象的引用,比如对数据库、搜索引擎的查询等等。通常来说,URL可以由协议名、主机、端口和资源组成,以下为格式:
protocol://host:port/resource
URL类提供了多个构造器用于创建URL对象,一旦获得了URL对象之后,就可以调用如下常用方法来访问该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。
示例、
网络权限
首先我们要知道,连接网络资源肯定是需要访问互联网的,这就涉及到网络权限的问题了。这需要我们在AndroidManifest.xml中添加以下授权代码:
<!--授权网络权限-->
<user-permission android:name="android.permission.INTERNET"/>
布局文件和Java部分
我们先把activity_main.xml中的布局修改一下
<?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>
接着我们在MainActivity.java中,写下调用接口的方法,并将它在文本框显示出来
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 "";
}
}
结果
以下就是代码的效果
林泽彬
原文链接:https://blog.csdn.net/m0_71507626/article/details/128174851