GDPU Android移动应用 访问网络

接到网络,开启你的访问之旅。

WebView的简单使用

WebView的简单使用,创建一个部件,上面一个button,下面一个webview布满整个屏幕,设置Web View的属性,使其可以执行Javascript(自己尝试设置其他属性)。点击Button在Web View中显示URL为www.gdpu.edu.cn的内容。

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    @SuppressLint("SetJavaScriptEnabled")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        var btnShowWebView = findViewById<Button>(R.id.btnShowWebView)
        var webView = findViewById<WebView>(R.id.webview)

        btnShowWebView.setOnClickListener {
            webView.settings.javaScriptEnabled = true
            webView.webViewClient = WebViewClient()
            webView.loadUrl("https://www.gdpu.edu.cn")
        }
    }
}
<?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/btnShowWebView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="点击展示GDPU主页" />

    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

别忘了在AndroidManifest.xml加权限配置。

    <!-- 权限声明 -->
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <application>
    </application>

OkHttp访问

 使用OkHttp访问以下接口,获取Aspirin化合物的JSON格式数据。

package com.example.ohtt

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONArray
import kotlin.concurrent.thread

class OkHttpActivity : AppCompatActivity() {

    private lateinit var responseText: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_okhttp)

        responseText = findViewById(R.id.responseText)
        val btnShowAspirin = findViewById<Button>(R.id.btnShowAspirin)
        btnShowAspirin.setOnClickListener {
            sendRequestWithOkHttp()
        }
    }

    private fun sendRequestWithOkHttp() {
        // 需要在后台线程中执行网络请求
        thread {
            try {
                val client = OkHttpClient()  // 使用 OkHttpClient 实例

                // 构造请求对象,指定请求的 URL
                val request = Request.Builder()
                    .url("https://pubchem.ncbi.nlm.nih.gov/sdq/sdqagent.cgi?infmt=json&outfmt=json&query={%22download%22:%22*%22,%22collection%22:%22compound%22,%22where%22:{%22ands%22:[{%22*%22:%22aspirin%22}]},%22order%22:[%22relevancescore,desc%22],%22start%22:1,%22limit%22:10000000,%22downloadfilename%22:%22PubChem_compound_text_aspirin%22}")
                    .build()

                // 通过 OkHttpClient 执行请求并获取响应
                val response = client.newCall(request).execute()

                // 获取响应体的字符串
                val responseData = response.body?.string()

                // 如果响应数据不为空,则调用解析方法
                if (responseData != null) {
                    parseJsonObject(responseData)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun parseJsonObject(jsonData: String) {
        try {
            // 将响应数据转换为 JSON 数组
            val jsonArray = JSONArray(jsonData)
            for (i in 0 until jsonArray.length()) {
                val jsonObject = jsonArray.getJSONObject(i)
                val name = jsonObject.getString("cmpdname")
                if (name == "Aspirin") {
                    runOnUiThread {
                        // 设置 TextView 显示整个 JSON 对象
                        responseText.text = jsonObject.toString()
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}
<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=".OkHttpActivity">

    <Button
        android:id="@+id/btnShowAspirin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="点击获取Aspirin化合物的JSON格式数据" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/responseText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </ScrollView>

</LinearLayout>

别忘了在build.gradle文件导入依赖配置。

    implementation "com.google.code.gson:gson:2.10"
    implementation "com.squareup.okhttp3:okhttp:4.10.0"

GSON解析

使用GSON解析以上获取的JSON数据。解析里面的cid标签,并将cid==2244的化合物对应的cid、cmpdname、mw和mf数据读取出来,用多个TextView按适当的界面风格排版,并分别显示出来。(提示:cid为Chemical ID,cmpdname为Compound Name,mw为Molecular Weight,mf为Molecular Formula)

class App(
    val cid: String,
    val cmpdname: String,
    val mw: String,
    val mf: String)
import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import okhttp3.OkHttpClient
import okhttp3.Request
import kotlin.concurrent.thread

class GsonActivity : AppCompatActivity() {
    private lateinit var textCid: TextView
    private lateinit var textCmpdname: TextView
    private lateinit var textMw: TextView
    private lateinit var textMf: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_gson)

        textCid = findViewById(R.id.textCid)
        textCmpdname = findViewById(R.id.textCmpdname)
        textMw = findViewById(R.id.textMw)
        textMf = findViewById(R.id.textMf)
        val btnShowAspirin = findViewById<Button>(R.id.btnShowAspirin)
        btnShowAspirin.setOnClickListener {
            sendRequestWithOkHttp()
        }
    }

    private fun sendRequestWithOkHttp() {
        thread {
            try {
                val client = OkHttpClient()
                val request = Request.Builder()
                    .url("https://pubchem.ncbi.nlm.nih.gov/sdq/sdqagent.cgi?infmt=json&outfmt=json&query={%22download%22:%22*%22,%22collection%22:%22compound%22,%22where%22:{%22ands%22:[{%22*%22:%22aspirin%22}]},%22order%22:[%22relevancescore,desc%22],%22start%22:1,%22limit%22:10000000,%22downloadfilename%22:%22PubChem_compound_text_aspirin%22}")
                    .build()
                val response = client.newCall(request).execute()
                val responseData = response.body?.string()
                if (responseData != null) {
                    parseJSONWithGSON(responseData)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun parseJSONWithGSON(jsonData: String) {
        try {
            val gson = Gson()
            val typeOf = object : TypeToken<List<App>>() {}.type
            val appList = gson.fromJson<List<App>>(jsonData, typeOf)
            for (app in appList) {
                if (app.cid == "2244") {
                    runOnUiThread {
                        textCid.text = app.cid
                        textCmpdname.text = app.cmpdname
                        textMw.text = app.mw
                        textMf.text = app.mf
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}
<?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=".GsonActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="70dp">

        <Button
            android:id="@+id/btnShowAspirin"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="点击显示cid==2244化合物数据" />

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="40dp"
        android:layout_marginBottom="20dp"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/cid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="25sp"
            android:text="cid:" />

        <TextView
            android:id="@+id/textCid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="25sp"
            android:layout_marginStart="25dp" />

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="40dp"
        android:layout_marginBottom="20dp"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/cmpdname"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="25sp"
            android:text="cmpdname:" />

        <TextView
            android:id="@+id/textCmpdname"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="25sp"
            android:layout_marginStart="25dp" />

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="40dp"
        android:layout_marginBottom="20dp"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/mw"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="25sp"
            android:text="mw:" />

        <TextView
            android:id="@+id/textMw"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="25sp"
            android:layout_marginStart="25dp" />

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="40dp"
        android:layout_marginBottom="20dp"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/mf"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="25sp"
            android:text="mf:" />

        <TextView
            android:id="@+id/textMf"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="25sp"
            android:layout_marginStart="25dp" />

    </LinearLayout>

</LinearLayout>

 实验心得

应当果断的。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值