Android HttpURLConnection GET 请求

从前面的章节中我们学习到,Android 提供了 HttpURLConnection 来处理 HTTP 请求操作,这章节我们就使用它来完成一个简单的 HTTP GET 请求吧

Android HttpURLConnection GET 请求

我们要请求的网址是 https://www.twle.cn/dy/text/getpost?lang=Android


  1. 创建一个 空的 Android 项目 cn.twle.android.HttpGet

  2. 修改 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">
    
        <EditText
            android:id="@+id/ms_url"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="请输入你要获取的网址"
            android:text="https://www.twle.cn/dy/text/getpost?lang=Android" />
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
    
            <Button
                android:id="@+id/btn_get"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:hint="加载" />
    
            <Button
                android:id="@+id/btn_source"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:hint="源码" />
    
            <Button
                android:id="@+id/btn_headers"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:hint="响应头" />
    
        </LinearLayout>
    
        <ScrollView
            android:id="@+id/ms_scroll"
            android:padding="16dp"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="gone">
    
            <TextView
                android:id="@+id/ms_data_content"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
        </ScrollView>
    
        <WebView
            android:id="@+id/ms_webview"
            android:padding="16dp"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    
    </LinearLayout>
    
  3. 然后在 MainActivity.java 目录下创建 WebHelper.java

    package cn.twle.android.httpget;
    
    import java.io.BufferedInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.List;
    import java.util.Map;
    
    public class WebHelper {
    
        // 获取网页的 html 源代码
    
        public static String getHtml(String path) throws Exception {
    
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("GET");
    
            if (conn.getResponseCode() == 200)
            {
                InputStream in = conn.getInputStream();
    
                BufferedInputStream bis = new BufferedInputStream(in);
                ByteArrayOutputStream buf = new ByteArrayOutputStream();
                int result = bis.read();
                while(result != -1) {
                    buf.write((byte) result);
                    result = bis.read();
                }
    
                return buf.toString("UTF-8");
            }
    
            return null;
        }
    
        // 获取 HTTP 的请求头和响应头
    
        public static String getHeaders(String path) throws Exception {
    
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("GET");
    
            StringBuilder sb = new StringBuilder();
            Map<String,List<String>> headers;
    
            headers = conn.getHeaderFields();
    
            for (Map.Entry<String,List<String>> entry : headers.entrySet()) {
    
                String key = entry.getKey();
    
                if ( key != null ) {
                    sb.append(key + ":");
                }
    
                for (String s : entry.getValue()) {
                    sb.append(s + " ");
                }
                sb.append("\n");
            }
    
            return sb.toString();
    
        }
    }
    
  4. 修改 AndroidManifest.xml 加上网络权限

    <uses-permission android:name="android.permission.INTERNET" />
    
  5. 最后修改 MainActivity.java 完善各种逻辑

    package cn.twle.android.httpget;
    
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.support.v7.app.AppCompatActivity;
    import android.view.View;
    import android.webkit.WebView;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ScrollView;
    import android.widget.TextView;
    import android.widget.Toast;
    
    public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    
        private TextView ms_data_content;
        private Button btn_get,btn_source,btn_headers;
        private EditText ms_url;
        private WebView ms_webview;
        private ScrollView ms_scroll;
        private String detail = "";
        private boolean flag = false;
    
        // 用于刷新界面
        private Handler handler = new Handler() {
            public void handleMessage(android.os.Message msg) {
                switch (msg.what) {
                    case 0x001:
                        hideAllWidget();
                        ms_scroll.setVisibility(View.VISIBLE);
                        ms_data_content.setText(detail);
                        Toast.makeText(MainActivity.this, "响应头加载完毕", Toast.LENGTH_SHORT).show();
                        break;
    
                    case 0x002:
                        hideAllWidget();
                        ms_scroll.setVisibility(View.VISIBLE);
                        ms_data_content.setText(detail);
                        Toast.makeText(MainActivity.this, "HTML代码加载完毕", Toast.LENGTH_SHORT).show();
                        break;
                    case 0x003:
                        hideAllWidget();
                        ms_webview.setVisibility(View.VISIBLE);
    
                        Bundle bd = (Bundle)msg.getData();
                        ms_webview.loadUrl(bd.getString("url"));
                        Toast.makeText(MainActivity.this, "网页加载完毕", Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        break;
                }
            }
    
            ;
        };
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            bindViews();
        }
    
        private void bindViews() {
    
            btn_get =  (Button) findViewById(R.id.btn_get);
            btn_source = (Button) findViewById(R.id.btn_source);
            btn_headers = (Button) findViewById(R.id.btn_headers);
    
            ms_url = (EditText) findViewById(R.id.ms_url);
    
            ms_data_content = (TextView) findViewById(R.id.ms_data_content);
            ms_webview = (WebView) findViewById(R.id.ms_webview);
            ms_scroll = (ScrollView) findViewById(R.id.ms_scroll);
    
            btn_headers.setOnClickListener(this);
            btn_get.setOnClickListener(this);
            btn_source.setOnClickListener(this);
    
        }
    
        // 定义一个隐藏所有控件的方法:
        private void hideAllWidget() {
            ms_scroll.setVisibility(View.GONE);
            ms_webview.setVisibility(View.GONE);
        }
    
        @Override
        public void onClick(View view) {
    
            Bundle bd = new Bundle();
            bd.putString("url",ms_url.getText().toString());
    
            Message msg = new Message();
            msg.setData(bd);
    
            switch (view.getId()) {
                case R.id.btn_headers:
                    new Thread() {
                        public void run() {
                            try {
    
                                detail = WebHelper.getHeaders(ms_url.getText().toString());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            handler.sendEmptyMessage(0x001);
                        };
                    }.start();
                    break;
    
                case R.id.btn_source:
                    new Thread() {
                        public void run() {
                            try {
    
                                detail = WebHelper.getHtml(ms_url.getText().toString());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            handler.sendEmptyMessage(0x002);
                        };
                    }.start();
                    break;
                case R.id.btn_get:
                        msg.what = 0x003;
                    break;
            }
    
            handler.sendMessage(msg);
        }
    }
    
    1. 我们使用 Handler 完成异步更新 UI

    2. 使用 WebView 加载网络,嗯,这个还没学到,后面我们会详解

注意: Android 不允许在非 UI 线程中进行 UI 操作

Android 基础教程

关于   |   FAQ   |   我们的愿景   |   广告投放   |  博客

  简单教程,简单编程 - IT 入门首选站

Copyright © 2013-2022 简单教程 twle.cn All Rights Reserved.