如何解决错误`java.net.ConnectException: Failed to connect to localhost/127.0.0.1:8000`
Posted
技术标签:
【中文标题】如何解决错误`java.net.ConnectException: Failed to connect to localhost/127.0.0.1:8000`【英文标题】:How to solve the error `java.net.ConnectException: Failed to connect to localhost/127.0.0.1:8000` 【发布时间】:2021-01-22 15:49:55 【问题描述】:我目前正在开发一个使用android-studio
和Kotlin
的应用程序以及一个使用django-rest-framework
的API 系统。
我想使用 android 模拟器访问我的本地服务器 127.0.0.1
以从 API 方法中获取一些值。
我检查了堆栈溢出站点和其他站点中的一些问题,并参考一些文章设置了我的代码,例如在AndroidManifest.xml
中添加一些代码,创建network_security_config.xml
,更改Android emulator
的代理和更改 Django rest framework
项目中的一些代码。
即使当我点击本地服务器中的端点时,我也有如下错误代码:
2020-10-07 22:37:39.318 7247-7247/com.sample.apitest I/System.out: checked
2020-10-07 22:37:39.358 7247-7280/com.sample.apitest D/NetworkSecurityConfig: Using Network Security Config from resource network_security_config debugBuild: true
2020-10-07 22:37:39.392 7247-7280/com.sample.apitest W/System.err: java.net.ConnectException: Failed to connect to localhost/127.0.0.1:8000
2020-10-07 22:37:39.394 7247-7280/com.sample.apitest W/System.err: at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:143)
2020-10-07 22:37:39.394 7247-7280/com.sample.apitest W/System.err: at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:112)
2020-10-07 22:37:39.394 7247-7280/com.sample.apitest W/System.err: at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:184)
2020-10-07 22:37:39.395 7247-7280/com.sample.apitest W/System.err: at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
2020-10-07 22:37:39.395 7247-7280/com.sample.apitest W/System.err: at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
2020-10-07 22:37:39.395 7247-7280/com.sample.apitest W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)
2020-10-07 22:37:39.396 7247-7280/com.sample.apitest W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224)
2020-10-07 22:37:39.396 7247-7280/com.sample.apitest W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)
2020-10-07 22:37:39.396 7247-7280/com.sample.apitest W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:127)
2020-10-07 22:37:39.397 7247-7280/com.sample.apitest W/System.err: at com.sample.apitest.MainActivity$HitAPITask.doInBackground(MainActivity.kt:49)
2020-10-07 22:37:39.397 7247-7280/com.sample.apitest W/System.err: at com.sample.apitest.MainActivity$HitAPITask.doInBackground(MainActivity.kt:39)
2020-10-07 22:37:39.397 7247-7280/com.sample.apitest W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:333)
2020-10-07 22:37:39.397 7247-7280/com.sample.apitest W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:266)
2020-10-07 22:37:39.397 7247-7280/com.sample.apitest W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
2020-10-07 22:37:39.397 7247-7280/com.sample.apitest W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
2020-10-07 22:37:39.398 7247-7280/com.sample.apitest W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
2020-10-07 22:37:39.398 7247-7280/com.sample.apitest W/System.err: at java.lang.Thread.run(Thread.java:764)
我该如何解决这个错误?
代码如下:
Android 项目
模拟器设置
AndroidManifest.xml
<?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.sample.apitest">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:networkSecurityConfig="@xml/network_security_config"
android:usesCleartextTraffic="true"
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"
tools:ignore="GoogleAppIndexingWarning"
tools:targetApi="n">
<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>
network_security_config.xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">localhost</domain>
</domain-config>
</network-security-config>
MainActivity.kt
package com.sample.apitest
import android.os.AsyncTask
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import org.json.JSONException
import org.json.JSONObject
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.MalformedURLException
import java.net.URL
class MainActivity : AppCompatActivity()
var name: TextView? = null
override fun onCreate(savedInstanceState: Bundle?)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
name = findViewById(R.id.textView)
val button = findViewById<Button>(R.id.button)
button.setOnClickListener
println("checked")
HitAPITask().execute("http://localhost:8000/api/name/")
inner class HitAPITask : AsyncTask<String, String, String>()
override fun doInBackground(vararg params: String?): String?
var connection: HttpURLConnection? = null
var reader: BufferedReader? = null
val buffer: StringBuffer
try
val url = URL(params[0])
connection = url.openConnection() as HttpURLConnection
connection.connect()
val stream = connection.inputStream
reader = BufferedReader(InputStreamReader(stream))
buffer = StringBuffer()
var line: String?
while (true)
line = reader.readLine()
if (line == null)
break
buffer.append(line)
var jsonText = buffer.toString()
val jsonObj = JSONObject(jsonText)
val plant_name: String = jsonObj.getString("name")
return plant_name
catch (e: MalformedURLException)
e.printStackTrace()
catch (e: IOException)
e.printStackTrace()
catch (e: JSONException)
e.printStackTrace()
finally
connection?.disconnect()
try
reader?.close()
catch (e: IOException)
e.printStackTrace()
return null
override fun onPostExecute(result: String?)
super.onPostExecute(result)
if (result == null) return
name!!.text = result
build.gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android
compileSdkVersion 28
defaultConfig
applicationId "com.sample.apitest"
minSdkVersion 16
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
buildTypes
release
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
dependencies
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:2.0.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
Django REST 框架项目
项目/settings.py
#...
INSTALLED_APPS = [
#...
'corsheaders',
]
MIDDLEWARE = [
#...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
]
CORS_ORIGIN_WHITELIST = [
'http://10.0.2.2:8000'
]
API 端点
[ Method = GET ] http://127.0.0.1:8000/api/name/
"name": "myName.",
安卓工作室:3.3.2
蟒蛇:3.7.5
django-cors-headers: 2.4.0
djangorestframework:3.8.2
【问题讨论】:
hmmmlocalhost
是模拟器本身
这能回答你的问题吗? How to connect to my http://localhost web server from Android Emulator
@Ryan M,谢谢你的评论,我已经提到了这个问题。但我无法解决我的错误...
【参考方案1】:
尝试打开cmd,然后在上面写ipconfig
之后,您获得了本地 IP 地址,然后尝试输入您的代码
例如,您从 cmd 获得 192.168.1.2,然后将其放入您的代码中,如下所示:
HitAPITask().execute("http://192.168.1.2/api/name/")
【讨论】:
感谢您的回答,在我将代码更改为您的回答后,错误消息更改为 ` W/System.err: org.json.JSONException: Value ype java.lang.字符串无法转换为 JSONObject` 您的连接问题已解决,但是,我认为您的 API 返回一个错误,通过 Postman 检查您的返回 API,如果它与您的 logcat 持续存在,那么它的问题来自您的 API 返回以上是关于如何解决错误`java.net.ConnectException: Failed to connect to localhost/127.0.0.1:8000`的主要内容,如果未能解决你的问题,请参考以下文章