Android学习之使用HTTP协议访问网络之HttpURLConnection

#转自第一行代码—郭霖
首先new出一个URL对象,传入目标对象的网络地址,再new一个HttpURLConnection的实例,然后调用URL的openConnection()方法即可。如下代码所示:

 URL url = new URL("https://www.baidu.com/");
 HttpURLConnection connection = null;
 connection = (HttpURLConnection) url.openConnection();

在得到HttpURLConnection的实例后,我们设置HTTP请求使用 GET 还是 POST。

GET 希望从服务器获取数据
POST 希望提交数据给服务器
connection.setRequestMethod("GET");//从服务器获取数据

接下来可设置一些参数,常用的有设置连接超时,设置读取超时的毫秒数等等:

connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);

接着调用getInputStream()方法可以获取到服务器返回的输入流,然后就是对输入流进行读取,如下:

InputStream in = connection.getInputStream();

最后调用disconnect()方法将这个HTTP连接关闭掉

connection.disconnect();

具体代码实现
activity_main.xml

<?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"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <Button
        android:id="@+id/sendRequestBtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/send_request"/>
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/responseText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </ScrollView>
</LinearLayout>

MainActivity.java

package com.example.lbstest;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.nio.BufferUnderflowException;

public class MainActivity extends AppCompatActivity {
    private Button sendRequestBtn;
    private TextView responseText;
    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sendRequestBtn = findViewById(R.id.sendRequestBtn);
        responseText = findViewById(R.id.responseText);
        sendRequestBtn.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("https://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 reponse = new StringBuilder();
                    String line;
                    while((line = reader.readLine()) != null){
                        reponse.append(line);
                    }
                    showResponse(reponse.toString());

                } catch (MalformedURLException | ProtocolException e) {
                    e.printStackTrace();
                } catch (IOException 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() {
                responseText.setText(response);
            }
        });
    }

}
上一篇:HttpsURLConnection HttpURLConnection下载图片


下一篇:JDK对Http协议的Keep-Alive的支持,以JDK8为例