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;
    
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值