Android studio-學習-004-HttpURLConnection-實例-請求網頁

Android studio-學習-004-HttpURLConnection-實例-請求網頁-2020-4-4
作爲演示的項目,都是新建的空項目 (Empty Activity) 爲例開始修改

一、訪問網絡設置

manifests->AndroidMainfest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.login_01">

    <uses-permission android:name="android.permission.INTERNET" />        //添加的
    <application
        android:usesCleartextTraffic="true"                               //添加的
        android:allowBackup="true"                                     
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

二、修改java類

MainActivity

package com.example.login_01;          //根據自己的包名自己改
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    TextView responseText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button sendRequest = (Button) findViewById(R.id.send_request);
        responseText = (TextView) findViewById(R.id.response_text);
        sendRequest.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.send_request) {
            sendRequestWithURLConnection();
        }
    }

    private void sendRequestWithURLConnection() {
        //開啓線程來發起網絡請求
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try{
                    URL url = new URL("https://www.ancientcloud.club");
                    //獲取HttpURLConnection實例
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    //設置連接超時
                    connection.setConnectTimeout(8000);
                    //設置讀取超時的毫秒數
                    connection.setReadTimeout(8000);
                    //獲取到服務器返回的輸入流,字節輸入流InputStream對象
                    InputStream in = connection.getInputStream();
                    //下面對獲取到的輸入流進行讀取
                    reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    showResponse(response.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if(reader != null) {
                        try{
                            reader.close();
                        } catch(IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if(connection != null) {
                        connection.disconnect(); //將Http連接關閉掉
                    }
                }
            }
        }).start();
    }

    private void showResponse(final String response) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //在這裏進行UI操作,將結果顯示到界面上
                responseText.setText(response);
            }
        });
    }
}

三、修改xml

res->layout->activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/send_request"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send Request"/>

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

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

</LinearLayout>

四、效果

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章