HttpURLconnection的使用

一、HTTP协议

  HTTP(Hyper Text Transfer Protocol),即超文本传输协议,它规定了浏览器 和万维网服务器之间相互通信的规则。

 当我们使用手机客户端访问百度网站时,会发送一个HTTP请求。当服务器端接 收到这个请求后,会做出响应并将百度首页返回给客户端浏览器。这个请求和响应的 过程就是HTTP通信的过程。

 二、简介

        在Android开发中网络请求是最常用的操作之一, Android SDK中对HTTP(超文 本传输协议)也提供了很好的支持,这里包括两种接口:

        1、标准Java接口(java.NET)——HttpURLConnection,可以实现简单的基于 URL请求、响应功能;

         2、Apache接口(org.appache.http)——HttpClient,存在API数量过多,扩展困 难等缺点。

        因此,在android 6.0系统中,Google将HttpClient移除了。Google建议使用 HttpURLconnection迚行网络访问操作。

HttpURLconnection是基于http协议的,支持get,post,put,delete等各种请求 方式,最常用的就是get和post请求。

三、HttpURLConnection的基本用法

   1、步骤1:获得HttpURLConnection类的实例

        由于HttpURLConnection类是一个抽象类,丌能直接实例化对象,因此需要使用 URL的openConnection()方法创建具体的实例。

//1. 使用new关键字创建一个URL对象,并传入目标的网络地址

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

//2.调用openConnection()方法,创建HttpURLConnection类的实例

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

  2、步骤2:设置HTTP请求参数

函数说明
setRequestMethod()设置请求参数,主要有两种方式:GET请求、POST请求
setConnectTimeOut()设置连接超时时间
setReadTimeOut()设置读取超时时间
setRequestProperty()设置请求头参数,主要是添加HTTP请求HEAD中的一些参数
setDoOutput()设置是否向HttpURLConnection输出,对于POST请求,参数要放在 http正文中,因此需要设为true,默认情冴下为false
setDoInput()设置是否从HttpURLConnection读入,默认情冴下为true

  3、步骤3:调用connect()连接进程资源

   4、步骤4:利用getInputStream()访问资源(GET请求)

        使用getInputStream()方法只是得到一个流对象,并丌是数据,丌过我们可以从流 中读出数据。

注意 从这个流对象中只能读取一次数据,第二次读取时将会得到空数据。

  步骤4:利用getOutputStream()传输POST消息(POST请求)

        使用getOutputStream()方法用来传输POST消息,该方法得到的是一个输出流,该 输出流中保存的是发送给服务器端的数据。

注意 connection.setDoOutput(true); //允许写出

  5、步骤5:关闭HttpURLConnection连接

所有的操作全部完成后,就可以调用disconnect()方法将这个HTTP连接关闭掉。                                                 if(connection != null)                                                                           onnection.disconnect();

注意

(1)声明网络权限:

(2)网络请求,需要单独开辟一个子线程,然后等到数据返回成功后回到 主线程迚行UI操作。

四、代码部分

  1、layout1.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/tv"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

  2、activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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: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" />

</android.support.constraint.ConstraintLayout>

  3、MainActivity.java

package com.example.zshttpurlconnection;

import android.support.v7.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.layout1);

        //对象和布局文件上的控件进行绑定
        textView = findViewById(R.id.tv);

        //定义一个匿名的子线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                //抓取百度首页的数据
                HttpURLConnection connection =null;
                try{
                    //1.获取HttpURLConnection类的实例
                    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 responseCode = connection.getResponseCode();
                    if(responseCode == 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);
                        }
                        //4.4 将服务器返回的数据显示到TextView控件上
                       // textView.setText(sb.toString());    //写法是错误的
                        showResponse(sb.toString());
                    }

                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    if(connection != null){
                        connection.disconnect();
                    }
                }

            }
        }).start();
    }

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

    }
}

  • 4
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

撩得Android一次心动

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

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

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

打赏作者

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

抵扣说明:

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

余额充值