android中使用http协议访问网络

本文介绍如何使用Android中的HttpURLConnection类实现HTTP GET请求。通过一个简单的示例项目展示了从创建连接到接收服务器响应的全过程,并强调了正确关闭资源的重要性。

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

在android应用中可以通过HttpURLConnection类来使用http协议访问网络,大概的流程是这样的。

1、获取HttpURLConnection的实例,通过一个URL对象调用openConnection()方法来获得

2、通过HttpURlConnection实例的setRequestMethod()方法设置http请求所用的方法,一般为GET或POST

3、使用HttpURLConnection实例的getInputStream()方法来获取服务器返回的输入流

4、调用HttpURLConnection实例的disconnect()来关闭http连接

接下来举一个小例子,新建一个HttpURLConnection项目:

activity_main.xml中的代码如下:

<?xml version="1.0" encoding="utf-8"?>
<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/sendRequest"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send Requset"
        android:textAllCaps="false"/>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/responseData"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </ScrollView>

</LinearLayout>

布局中添加了一个按钮用于触发发送http请求事件,ScrollView控件中放置一个TextView控件用于显示从服务器接受到的响应文本信息。


AndroidManifest.xml中的代码如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tangliang.httpurlconnection">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

由于程序要访问网络,所以这里还是要申请INTERNET权限


MainActivity中的代码如下:

package com.tangliang.httpurlconnection;

import android.renderscript.ScriptGroup;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.view.menu.ExpandedMenuView;
import android.view.View;
import android.widget.Button;
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 responseData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button sendRequest = (Button) findViewById(R.id.sendRequest);
        responseData = (TextView) findViewById(R.id.responseData);
        sendRequest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendRequestWithHttpURLConnection();
            }
        });
    }

    private void sendRequestWithHttpURLConnection(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try{
                    URL url = new URL("http://blog.youkuaiyun.com/a18779148177");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(5000);
                    connection.setReadTimeout(5000);
                    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 (Exception e){
                            e.printStackTrace();
                        }
                    }
                    if(connection != null){
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }
    private void showResponse(final String response){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                responseData.setText(response);
            }
        });
    }
}

MainActivity中有几点需要注意,一是在接受响应完成后要关闭流和HttpURLConnection对象,二是不能在UI线程中进行耗时操作,否则程序会崩溃,三 是不能在子线程中更新UI,必须要切换回UI线程中才能更新UI。


程序运行,并按下发送请求按钮后的结果图如下:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值