Android 通过HttpURLConnection访问Http协议网络

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

在这里插入图片描述

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

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

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

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>
  • 5
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Android Studio中使用HTTP访问网络通常涉及到使用HttpURLConnection或者HttpClient进行网络请求操作。首先,需要在AndroidManifest.xml文件中添加网络权限声明,以允许应用程序进行网络访问。接着,需要在Java代码中创建一个新的线程或者异步任务来执行网络请求操作,因为不能在主线程中执行网络请求,否则会导致程序崩溃。 使用HttpURLConnection进行网络请求时,需要创建一个URL对象,然后通过openConnection()方法得到HttpURLConnection对象。接着,可以设置请求的方法(GET、POST等)、请求头、请求参数等,并发送请求。收到响应后,可以通过getInputStream()方法获取输入流,然后解析和处理服务器返回的数据。 另一种方法是使用HttpClient进行网络请求。需要创建一个DefaultHttpClient对象,并通过HttpGet或HttpPost方法创建请求对象。之后可以设置请求头、请求参数等,并使用execute()方法执行请求。同样,收到响应后可以通过获取输入流来处理返回的数据。 需要注意的是,为了避免在主线程中进行网络请求,可以使用AsyncTask或者Thread来进行异步操作。同时,为了适配Android 9.0及以上版本的系统,还需要在网络请求时进行网络安全性配置,例如使用HTTPS协议或者在清单文件中声明网络安全配置。 总之,在Android Studio中使用HTTP访问网络需要遵循网络请求的基本操作步骤,并且需要适配最新的系统版本和网络安全性规范。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Teacher.Hu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值