第一行代碼 9.2.2使用OkHttp
哇哇哇 終於 找到這個坑坑 實現了該出現的東西
這一章 是使用網絡技術,前面的使用HttpURLConnection 很順利就實現了書上的東西。
但是在進入使用OkHttp後,按照書上敲完代碼,運行時點擊請求按鈕,沒有了任何反應。
查看了OkHttp 需要依賴okio這個東西,添加後還是沒有什麼效果、
都是最新的版本:OkHttp的github地址:https://github.com/square/okhttp
Okio的github地址:https://github.com/square/okio
我的配置文件
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
implementation("com.squareup.okhttp3:okhttp:4.2.2")
implementation("com.squareup.okio:okio:2.4.2")
}
在嘗試後並沒得到自己想要的結果,隔了幾天,就在剛剛 查看日誌後,發現了這麼一個錯誤
W/System.err: java.net.UnknownServiceException: CLEARTEXT communication to www.baidu.com not permitted by network security policy
順着這個錯誤,通過查找得到了我想要的結果了。
先放鏈接:https://blog.csdn.net/qq_2300688967/article/details/81114201。
添加後就可以了。
原理我不清楚,我也纔開始學Android。
我的代碼:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.networktest">
<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"
------------------------------------
android:usesCleartextTraffic="true">
----------------------------------------
<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>