HttpURLConnection的简单用法

本文详细介绍如何使用HttpURLConnection发起GET请求并获取服务器响应。通过实例演示了如何设置请求超时、读取响应数据,并展示了如何在Android应用中正确处理UI更新。

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

 使用HttpURLConnection来访问网络,首先需要获取它的实例,它需要new 一个URL对象,例如URL url = new URL("http://www.baidu.com") ,再使用HttpURLConnection connection = (HttpURLConnection) url.openConnection();这个方法返回一个HttpURLConnection实例。之后就可以通过这个实例设置一些Http请求的属性和方法了:下面看下布局的写法:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/send_request"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send Request"/>
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/responese_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </ScrollView>
</LinearLayout>

这里面的一个控件ScrollView 由于手机屏幕不够大,可以通过滚动的形式查看屏幕外的内容。在设置一个TextView ,将服务器返回的数据显示出来。MainActivity中的核心代码:

private void sendRequestWithHttpURLConnection() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection =  null;
                BufferedReader reader = null;
                try {
                    URL url = new URL("http://www.baidu.com");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    //此时获取的是字节流
                    InputStream in = connection.getInputStream();
                    //对获取到的输入流进行读取
                    reader = new BufferedReader(new InputStreamReader(in)); //将字节流转化成字符流
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine())!= null) {
                        response.append(line);
                    }
                    showResponse(response.toString());

                } catch (Exception e ) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e ) {
                            e.printStackTrace();
                        }
                    }
                    if ( connection!= null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }
    private void showResponse(final  String response) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //在这里进行UI操作 
                responseText.setText(response);
            }
        });
    }

由于Android中是不允许在子线程中进行UI操作的,因此开启一个runOnUiThread线程,切回到主线程进行更新,最后声明一下网络权限,运行:

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值