关于HttpUrlConnection的学习与使用(1)

本文详细介绍了HTTP请求的基本概念及其两种常用请求方式GET和POST的区别,重点讲解了Java中HttpUrlConnection类的使用方法及步骤,包括如何通过该类实现对指定网站的GET和POST请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、HTTP请求的含义

  1. HTTP请求是客户端和服务端之间,发送请求和返回应答的标准(TCP);
  2. 客户端发出一个HTTP请求后,就与服务器建立起了TCP连接,服务端接受到请求并进行处理后返回给客户端相应数据。

注意点:HTTP常用的请求方式 get方式和post方式,其中get方式属于明文传参,不安全;post方式属于暗文传参,安全


二、HttpUrlConnection的含义

HttpUrlConnection是java的标准指定网站发送GET请求、POST请求类,HttpUrlConnection继承自URLConn,可用于向指定网站发送GET请求、POST请求,HttpUrlConnection在使用上相对简单,并且易于扩展,推荐好用。

三、使用HttpUrlConnection的步骤

  • 创建URL对象
  • 通过URL对象调用openConnection对象
  • HttpUrlConnection对象设置其他连接属性
  • HttpUrlConnection对象调用getInputStream()方法向服务器发送http请求并获取到服务器返回的输入流
  • 读取输入流,转化成String字符串

注意点:1.在Android中访问网络必须添加网络权限
2.在Android中访问网络必须在子线程中进行


四、使用HttpUrlConnection获取HTTP请求(以访问csdn网站为例)

1.首先在layout布局文件中定义一个Button控件

 <Button
        android:id="@+id/show_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

2.然后在主体类里定义控件,绑定ID,设置点击事件

private Button showBtn;
 private void bindID() {
        showBtn=findViewById(R.id.show_btn);
    }

3.在方法体里写方法,最后用log.e来测试

  public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        getWebInfo();     
                    }
                }).start();
            }
        });
    }

    private void getWebInfo() {
        try {
            // 1.找水源--URL
            URL url=new URL("http://www.youkuaiyun.com/");
            //2.开水闸--opeanConnection
            HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
            //3.建管道--InputStream
            InputStream inputStream=httpURLConnection.getInputStream();
            //4.建蓄水池--InputStreamReader
            InputStreamReader reader=new InputStreamReader(inputStream,"UTF-8");
            //5.水桶盛水--BufferReader
            BufferedReader bufferedReader=new BufferedReader(reader);

            StringBuffer stringBuffer=new StringBuffer();
            String temp=null;

            while((temp=bufferedReader.readLine())!=null){
                stringBuffer.append(temp);
            }

            bufferedReader.close();
            reader.close();
            inputStream.close();

            Log.e("MAIN",stringBuffer.toString());

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值