HttpURLConnection:从服务器获取数据、网络请求

本文介绍了一个简单的Android应用示例,展示了如何使用HttpURLConnection发起GET请求,并通过UI显示响应结果。该应用首先在AndroidManifest.xml中声明了Internet权限,然后在主Activity中设置了按钮和文本视图用于触发请求及展示响应。

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

1.声明权限

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

2.布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context="com.admin.networkdemo.MainActivity">

    <Button
        android:id="@+id/btn_send_request"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:text="发送请求"/>

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

</LinearLayout>

3.activity

public class MainActivity extends AppCompatActivity {

    public static final int SHOW_RESPONSE = 0;
    @BindView(R.id.btn_send_request)
    Button btnSendRequest;
    @BindView(R.id.tv_response)
    TextView tvResponse;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case SHOW_RESPONSE:
                    String response = (String) msg.obj;
                    //在这里进行UI操作,将结果显示到界面上
                    tvResponse.setText(response);
                    break;
            }
        }
    };

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

    @OnClick(R.id.btn_send_request)
    public void onViewClicked() {
        sendRequestWithHttpURLConnection();
    }

    /**
     * HttpURLConnection
     */
    private void sendRequestWithHttpURLConnection(){
        //开启线程来发动网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try{
                    URL url = new URL("https://www.baidu.com");
                    connection = (HttpURLConnection)url.openConnection();
                    connection.setRequestMethod("GET");//GET表示从服务器获取数据;POST表示向服务器提交数据
                    connection.setConnectTimeout(8000);//设置连接超时
                    connection.setReadTimeout(8000);//设置读取超时
                    InputStream in = connection.getInputStream();//获取到服务器返回的输入流
                    //下面对获取到的输入流进行读取
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null){
                        response.append(line);
                    }
                    Message message = new Message();
                    message.what = SHOW_RESPONSE;
                    //将服务器返回的结果存放到Message中
                    message.obj = response.toString();
                    handler.sendMessage(message);
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    if(connection != null){
                        connection.disconnect();//将HTTP连接关闭
                    }
                }
            }
        }).start();
        /*//向服务器提交用户名和密码
        connection.setRequestMethod("POST");
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        //每条数据都要以键值对的形式存在,数据与数据之间用&符号隔开
        out.writeBytes("username=admin&password=123");*/
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值