Android开发——网络请求(二)网络请求操作HttpURLConnection

软件效果图

输入网址,点击请求,在底部输出网址的响应code

实现代码

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.administrator.networkexcise.MainActivity">

    <EditText
        android:id="@+id/et_network_url"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入网址"
        android:textSize="16sp"
        android:textAllCaps="false" />
    
    <TextView
        android:layout_marginTop="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="测试HttpUrlConnection"
        android:textSize="20sp"
        android:textColor="@color/colorBlack"/>
    
    <LinearLayout
        android:layout_marginTop="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:textColor="@color/colorBlack"
            android:layout_weight="1"
            android:textSize="16sp"
            android:text="GET请求"
            android:onClick="testConnectionGet"/>
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:textColor="@color/colorBlack"
            android:layout_weight="1"
            android:textSize="16sp"
            android:text="POST请求"
            android:onClick="testConnectionPost"/>

    </LinearLayout>

    <EditText
        android:id="@+id/et_network_result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

MainActivity

package com.example.administrator.networkexcise;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class MainActivity extends AppCompatActivity {

    EditText et_network_url, et_network_result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        et_network_url = (EditText) findViewById(R.id.et_network_url);
        et_network_result = (EditText) findViewById(R.id.et_network_result);


    }

    /**
     * 测试HttpUrlConnection的Get请求
     *
     * @param view 1.   显示ProgressDialog
     *             2.   启动分线程
     *             3.   在分线程,发送请求,得到相应数据
     *             1).  得到path,并带上参数,name = Tom & age = 11
     *             2).  创建URL
     *             3).  打开连接,得到HttpURLConnection对象
     *             4).  设置请求方式,连接超时,读取数据超时
     *             5).  连接服务器
     *             6).  发请求,得到相应数据
     *             得到响应码必须是200才能读取
     *             得到InputStream,并读取成String
     *             4.  在主线程,显示得到的结果,消除Dialog
     */
    public void testConnectionGet(View view) {
        //1.   显示ProgressDialog
        final ProgressDialog progressDialog = ProgressDialog.show(this, null, "正在请求中···");
        //2.   启动分线程
        new Thread() {
            //3.   在分线程,发送请求,得到相应数据
            @Override
            public void run() {
                //创建流和连接
                InputStream inputStream = null;
                ByteArrayOutputStream baos = null;
                HttpURLConnection connection = null;
                try {
                    //1).  得到path
                    String path = et_network_url.getText().toString();
                    //2).  创建URL
                    URL url = new URL(path);
                    //3).  打开连接,得到HttpURLConnection对象
                    connection = (HttpURLConnection) url.openConnection();
                    //4).  设置请求方式,连接超时,读取数据超时
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(5000);
                    connection.setReadTimeout(6000);
                    //5).  连接服务器
                    connection.connect();
                    //6).  发请求,得到相应数据
                    //     得到输出流,写请求体。
                    //     得到响应码必须是200才能读取
                    int responseCode = connection.getResponseCode();
                    if (responseCode == 200) {
                        //     得到InputStream,并读取成String
                        inputStream = connection.getInputStream();
                        baos = new ByteArrayOutputStream();
                        byte[] buffer = new byte[1024];
                        int len = -1;
                        while ((len = inputStream.read(buffer)) != -1) {
                            baos.write(buffer, 0, len);
                            //休息0.1秒
                            SystemClock.sleep(100);
                        }
                        final String result = baos.toString();
                        //4.    在主线程,显示得到的结果,消除Dialog
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                et_network_result.setText(result);
                            }
                        });
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    //7)    关闭流,断开连接
                    try {
                        baos.close();
                        inputStream.close();
                        connection.disconnect();
                        progressDialog.dismiss();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

    /**
     * 测试HttpUrlConnection的Post请求
     *
     * @param view 1. 显示ProgressDialog
     *             2. 启动分线程
     *             3. 在分线程,发送请求,得到相应数据
     *             1). 创建path
     *             2). 创建URL对象
     *             3). 打开连接,得到HttpURLConnection对象
     *             4). 设置请求方式,连接超时,读取数据超时
     *             5). 连接服务器
     *             6). 发请求,得到响应
     *             得到响应码,必须是200才读取
     *             创建InputStream,并读取成String
     *             4.返回主线程,显示响应结果
     *             7). 关闭流,断开连接
     */
    public void testConnectionPost(View view) {
        //1. 显示ProgressDialog
        final ProgressDialog progressdialog = ProgressDialog.show(this, null, "请求中···");
        //2. 启动分线程
        new Thread() {
            //3. 在分线程,发送请求,得到相应数据
            @Override
            public void run() {
                HttpURLConnection connection = null;
                InputStream is = null;
                ByteArrayOutputStream baos = null;
                try {
                    super.run();
                    //1). 创建path
                    String path = et_network_url.getText().toString();
                    //2). 创建URL对象
                    URL url = new URL(path);
                    //3). 打开连接,得到HttpURLConnection对象
                    connection = (HttpURLConnection) url.openConnection();
                    //4). 设置请求方式,连接超时,读取数据超时
                    connection.setRequestMethod("POST");
                    //5). 连接服务器
                    connection.connect();
                    //6). 发请求,得到响应
                    int responseCode = connection.getResponseCode();
                    //得到响应码,必须是200才读取
                    if (responseCode == 200) {
                        //创建InputStream,并读取成String
                        is = connection.getInputStream();
                        baos = new ByteArrayOutputStream();
                        byte[] buffer = new byte[1024];
                        int len = -1;
                        while ((len = is.read(buffer)) != -1) {
                            baos.write(buffer, 0, len);
                        }
                        final String resuit = baos.toString();
                        //4.返回主线程,显示响应结果
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                et_network_result.setText(resuit);
                            }
                        });
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    //7). 关闭流,断开连接
                    connection.disconnect();
                    try {
                        is.close();
                        baos.close();
                        progressdialog.dismiss();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }
}

当然,还要授权网络

<!--网络权限-->
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

狮子座的程序员

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

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

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

打赏作者

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

抵扣说明:

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

余额充值