Android—HttpsURLConnection示例(Kotlin)

package com.example.networktest

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.*
import java.lang.StringBuilder
import java.net.URL
import javax.net.ssl.HttpsURLConnection

class MainActivity : AppCompatActivity() {
    private val TAG = MainActivity::class.java.simpleName
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        send_request.setOnClickListener {
            sendRequestWithHttpsURL()
        }
    }

    private fun sendRequestWithHttpsURL() {
        runBlocking {
            //启动一个新协程(阻塞的),也可以通过GlobalScope.launch启动一个顶层协程,这样就不用下面的切换线程操作
            withContext(Dispatchers.Default) {
                /* TODO 通过协程调度器把这段代码切换到线程池中的线程中去执行,runBlocking还是运行在主线程中
                 在Android4.0以后,会发现,只要是写在主线程(就是Activity)中的HTTP请求,运行时都会报错,这是因为Android
                 在4.0以后为了防止应用的ANR(Aplication Not Response)异常,Android这个设计是为了防止网络请求时间过长而导致界面假死的情况发生。*/

                /*TODO 为保证用户数据和设备的安全,Google针对下一代 Android 系统(Android P) 的应用程序,将要求默认使用加密连接,
                这意味着 Android P 将禁止 App 使用所有未加密的连接,因此运行 Android P 系统的安卓设备无论是接收或者发送流量,
                未来都不能明码传输,需要使用下一代(Transport Layer Security)传输层安全协议,而 Android Nougat 和 Oreo 则不受影响。
                因此在Android P 使用HttpUrlConnection进行http请求会出现以下异常:
                W/System.err: java.io.IOException: Cleartext HTTP traffic to **** not permitted
                使用OKHttp请求则出现:
                java.net.UnknownServiceException: CLEARTEXT communication ** not permitted by network security policy
                在Android P系统的设备上,如果应用使用的是非加密的明文流量的http网络请求,则会导致该应用无法进行网络请求,
                https则不会受影响,同样地,如果应用嵌套了webview,webview也只能使用https请求。

                针对这个问题,有以下三种解决方法:
                (1)APP改用https请求
                (2)targetSdkVersion 降到27以下
                (3)更改网络安全配置 */

                var connection: HttpsURLConnection? = null
                try {
                    connection = (URL("https://www.baidu.com").openConnection() as HttpsURLConnection).apply {
                        requestMethod = "GET"//设置请求方式
                        connectTimeout = 8000//设置连接超时时间
                        readTimeout = 8000//设置读取超时时间
                    }

                    connection.inputStream.bufferedReader().useLines {
                        it.forEach {
                            val sb = StringBuilder().apply {
                                append(it)
                            }
                            Log.d(TAG, "onCreate2: $sb")
                            showResponse(sb.toString())
                        }
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                } finally {
                    connection?.disconnect()
                }

            }
        }
    }

    private fun showResponse(response: String) {
        runOnUiThread {
            //在这里进行UI操作,将结果显示到界面上
            response_text.text = response
        }
    }

}

<?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=".MainActivity">

    <Button
        android:id="@+id/send_request"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send Request"
        android:textAllCaps="false" />

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

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

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

    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="false"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:ignore="GoogleAppIndexingWarning">
        <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>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
HttpsURLConnection 是 HttpURLConnection 的一个子类,用于在 Java 中进行 https 请求。与 HttpURLConnection 类似,HttpsURLConnection 也提供了对 http 请求的支持,并且可以通过 setRequestMethod() 方法设置请求方法(如 GET、POST 等)。不同的是,HttpsURLConnection 需要进行 SSL/TLS 握手,以确保通信的安全性。 以下是一个简单的示例,演示如何使用 HttpsURLConnection 发送 https 请求: ```java import javax.net.ssl.HttpsURLConnection; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; public class HttpsExample { public static void main(String[] args) throws Exception { String httpsUrl = "https://example.com"; URL url = new URL(httpsUrl); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); // 可以设置请求方法、超时时间等参数 con.setRequestMethod("GET"); con.setConnectTimeout(5000); con.setReadTimeout(5000); // 打印服务器返回的状态码 System.out.println("Response code: " + con.getResponseCode()); // 读取服务器返回的数据 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder content = new StringBuilder(); while ((inputLine = in.readLine()) != null) { content.append(inputLine); } in.close(); // 打印服务器返回的数据 System.out.println("Response content: " + content.toString()); } } ``` 需要注意的是,在实际使用中,可能需要设置 SSLContext、TrustManager 等参数,以确保 https 请求的安全性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值