Android 通过HttpURLConnection访问Http协议网络

本文目录

  • 第一步:添加网络访问权限
  • 第二步:使用HttpURLConnection访问网络
  • 代码示例

Android原生目前支持两种方式访问http协议的网络,第一种是HttpURLConnection,另外一种是oKHttp,下面来介绍一下用HttpURLConnection来访问访问http协议的方法

Android 通过HttpURLConnection访问Http协议网络_第1张图片

第一步:添加网络访问权限

AndroidManifest.xml文件中添加如下权限



http请求需要在 AndroidManifest.xml文件的application节点添加如下属性

android:usesCleartextTraffic="true"

第二步:使用HttpURLConnection访问网络

首先我们需要得到HttpURLConnection的实例,获取HttpURLConnection的方法如下

URL url = new URL("http://baidu.com");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

拿到HttpURLConnection的实例以后我们可以通过HttpURLConnection的实例来设置一些http请求的方式

urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(8000);
urlConnection.setRequestProperty("key","value");
方法名 含义
setRequestMethod 请求方式(常见的包括GET和POST等)
setConnectTimeout 请求超时时间
setRequestProperty 请求中带的参数

请求发送出去以后,我们就可以通过HttpURLConnection的实例拿到请求的返回数据

InputStream inputStream = urlConnection.getInputStream();// 字节流
Reader reader = new InputStreamReader(inputStream);//字符流
 BufferedReader bufferedReader = new BufferedReader(reader);// 缓存流

然后我们就可以从缓存流bufferedReader中读取数据

     StringBuilder result = new StringBuilder();;
     String temp;
     while ((temp = bufferedReader.readLine()) != null) {
         result.append(temp);
     }
     Log.i("MainActivity", result.toString());

读完数据以后不要忘记把数据流关闭哦

 			if (reader!=null){
		         try {
	                reader.close();
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
      		}
            if (inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedReader!=null){
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (urlConnection != null){
                urlConnection.disconnect();
            }

网络请求访问我们还需要放到子线程中去

      new Thread(){
        @Override
             public void run() {
                 super.run();
                 getNetwork();
             }
         }.start();  

把得到的数据切到主线程中用文本展示出来

  runOnUiThread(new Runnable() {
     @Override
           public void run() {
               mTextView.setText(result);
           }
       });

代码示例

完整代码如下

MainActivity.java

package com.lucashu.http;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

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

public class MainActivity extends AppCompatActivity {
    TextView mTextView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = findViewById(R.id.button);
        mTextView = findViewById(R.id.textView);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              new Thread(){
                  @Override
                  public void run() {
                      super.run();
                      getNetwork();
                  }
              }.start();
            }
        });

    }

    private void getNetwork() {
        InputStream inputStream = null;
        Reader reader = null;
        BufferedReader bufferedReader = null;
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL("http://baidu.com");
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setConnectTimeout(8000);
            urlConnection.setRequestProperty("key","value");

            inputStream = urlConnection.getInputStream();// 字节流
            reader = new InputStreamReader(inputStream);//字符流
            bufferedReader = new BufferedReader(reader);// 缓存流

            final StringBuilder result = new StringBuilder();;
            String temp;
            while ((temp = bufferedReader.readLine()) != null) {
                result.append(temp);
            }
            Log.i("MainActivity", result.toString());
             runOnUiThread(new Runnable() {
                 @Override
                 public void run() {
                     mTextView.setText(result);
                 }
             });
            inputStream.close();
            reader.close();
            bufferedReader.close();

        } catch (Exception e) {
            Log.i("MainActivity", e.getMessage());
            e.printStackTrace();
        }finally {
            if (reader!=null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedReader!=null){
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (urlConnection != null){
                urlConnection.disconnect();
            }
        }
    }
}

AndroidManifest.xml

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

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

    <application
        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"
        android:usesCleartextTraffic="true">
        <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>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.323" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="96dp"
        android:text="访问网络数据"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

你可能感兴趣的:(Android,#,Android基础)