http访问网络步骤 (HttpURLConnection方法)10 / 100

http访问网络步骤:

1,获取HttpURLConnection类的实例:

URL url = new URL("https://www.baidu.com);

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

2,设置Http请求参数

connection.setRequestMethod(“GET”);//设置请求的方式为GET

connection.setConnectTimeout(8000);//设置连接超时为8s

connection.setReadTimeout(8000);//设置读取操作超时为8s

3,调用connect()方法连接远程资源,并对服务器响应进行判断

connection.connect();

int resposCode = connection.getResponseCode():

if(responsCode==HttpURLConnection.HTTP_OK){

//进行数据读取操作

4,利用getInputStream方法访资源

//4.1利用getInputStream()获取响应流
InputStream in = connection.getInputStream();
//4.2构建BufferedReader对象
BufferedReader reader = new BufferedReader(new IntputStreamReader(in));
//4.3构建字符串对象,用来接收缓冲流中的数据
StringBuilder sb = new StringBuilder();
String line = null;
while((line= reader.readLine())!=null){
sb.append(line);//使用StringBuilder()方法进行动态叠加
}
//4.4将服务器返回的数据显示到页面上
showResponse(sb.toString());//定义一个showResponse()方法,在主线程里面完成UI操作,子线程不可以进行UI操作

private void showResponse(final String response){

//将服务器返回的数据回到UI线程,从而在textView控件中进行显示

runOnUiThread(new Runnable() {//该方法在线程中执行UI更新操作
@Override
public void run() {
//在这里进行UI操作,将结果显示到textView控件上(界面)
textView.setText(response);
}
});

}

finally{//finally任何情况都可以进行

//5.关闭HttpURLConnection连接

if(connection!=null)}{

connection.disconnect();

}

}

MainActivity.java

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.TextView;

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

public class MainActivity extends AppCompatActivity {
    private TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.tv1);
        //定义一个匿名的子线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                //抓取百度首页的数据,网络访问的数据可能会产生一些异常的情况,建议操作写在try里面
                try {
                    //1,获取HttpURLConnection的实例
                    //新建一个url
                    URL url = new URL("https://www.baidu.com");
                    connection = (HttpURLConnection) url.openConnection();
                    //2,设置http请求的参数
                    connection.setRequestMethod("GET");//设置请求方式为GET
                    connection.setConnectTimeout(8000);//设置连接超时为8s
                    connection.setReadTimeout(8000);//设置读取操作超时为8s
                    //3,调用connect()方法连接远程资源,并对服务器响应进行判断
                    connection.connect();
                    int responsCode=connection.getResponseCode();//得到服务器响应的一个代码
                    if (responsCode==HttpURLConnection.HTTP_OK){
                        //进行数据读取操作
                        //4,利用getInputStream方法访问资源
                        //4.1利用getInputStream()获取响应流
                        InputStream in=connection.getInputStream();
                        //4.2构建BufferedReader对象
                        BufferedReader reader=new BufferedReader(new InputStreamReader(in));//流的转换
                        //4.3构建字符串对象,用来接受缓冲流中的数据
                        StringBuilder sb = new StringBuilder();//动态拼接
                        String line=null;
                        while((line=reader.readLine()) != null){
                            sb.append(line);//使用StringBuilder的字符串可以实现动态的叠加
                        }
                        //4.4将服务器返回的数据显示到textView控件上
                        //textView.setText(toString());错误原因:UI的操作不能放在子线程操作,应该给放在主线程完成
                        showResponse(sb.toString());//自定义一个方法,将服务器返回的数据送给该方法
                    }
                }catch(Exception e){
                    e.printStackTrace();
                }finally {//5,关闭HttpURLConnection连接
                    if (connection != null){
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    private void showResponse(final String response) {
        //将服务器返回的数据返回到UI线程,从而在textView控件中进行显示
        runOnUiThread(new Runnable() {//该方法在线程中执行UI更新操作
            @Override
            public void run() {
                //在这里进行UI操作,将结果显示到textView控件上(界面)
                textView.setText(response);
            }
        });
    }
}

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"
    >
    <TextView
        android:id="@+id/tv1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
       />
</LinearLayout>

注意:
访问权限一定要在AndroidManifest.xml中加上!!!
请添加图片描述


版权声明:本文为qq_46912246原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。