title: How to solve the error `java.net.ConnectException: Failed to connect to localhost/127.0.0.1:8000`
body: <p>I'm currently developing an application using <code>android-studio</code> with <code>Kotlin</code> and an API system using <code>django-rest-framework</code>.</p>
  <p>I want to access my local server <code>127.0.0.1</code> with an android emulator to get some value from the API method.</p>
  <p>I checked some questions in the stack overflow site and other sites and I set my codes up referring to some articles, like adding some code in an <code>AndroidManifest.xml</code>, making a <code>network_security_config.xml</code>, changing a proxy of <code>Android emulator</code> and changing some code in <code>Django rest framework</code> project.</p>
  <p>even though when I hit an endpoint in my local server I have error codes like below:</p>
  <pre><code>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)
  </code></pre>
  <p>How could I solve this error?</p>
  <hr />
  <p>Here are the codes:</p>
  <p><strong>Android project</strong></p>
  <p>emulator settings
  <a href="https://i.stack.imgur.com/HwuID.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HwuID.png" alt="enter image description here" /></a></p>
  <p>AndroidManifest.xml</p>
  <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
  &lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
            xmlns:tools=&quot;http://schemas.android.com/tools&quot; package=&quot;com.sample.apitest&quot;&gt;
  
      &lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;
      &lt;uses-permission android:name=&quot;android.permission.ACCESS_NETWORK_STATE&quot;/&gt;
  
      &lt;application
              android:networkSecurityConfig=&quot;@xml/network_security_config&quot;
              android:usesCleartextTraffic=&quot;true&quot;
  
              android:allowBackup=&quot;true&quot;
              android:icon=&quot;@mipmap/ic_launcher&quot;
              android:label=&quot;@string/app_name&quot;
              android:roundIcon=&quot;@mipmap/ic_launcher_round&quot;
              android:supportsRtl=&quot;true&quot;
              android:theme=&quot;@style/AppTheme&quot;
              tools:ignore=&quot;GoogleAppIndexingWarning&quot;
              tools:targetApi=&quot;n&quot;&gt;
          &lt;activity android:name=&quot;.MainActivity&quot;&gt;
              &lt;intent-filter&gt;
                  &lt;action android:name=&quot;android.intent.action.MAIN&quot;/&gt;
  
                  &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot;/&gt;
              &lt;/intent-filter&gt;
          &lt;/activity&gt;
      &lt;/application&gt;
  &lt;/manifest&gt;
  </code></pre>
  <p>network_security_config.xml</p>
  <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
  &lt;network-security-config&gt;
      &lt;domain-config cleartextTrafficPermitted=&quot;true&quot;&gt;
          &lt;domain includeSubdomains=&quot;true&quot;&gt;localhost&lt;/domain&gt;
      &lt;/domain-config&gt;
  &lt;/network-security-config&gt;
  </code></pre>
  <p>MainActivity.kt</p>
  <pre><code>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&lt;Button&gt;(R.id.button)
  
          button.setOnClickListener {
              println(&quot;checked&quot;)
              HitAPITask().execute(&quot;http://localhost:8000/api/name/&quot;)
  
          }
      }
  
      inner class HitAPITask : AsyncTask&lt;String, String, String&gt;() {
  
          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(&quot;name&quot;)
  
                  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
          }
      }
  }
  </code></pre>
  <p>build.gradle</p>
  <pre><code>apply plugin: 'com.android.application'
  
  apply plugin: 'kotlin-android'
  
  apply plugin: 'kotlin-android-extensions'
  
  android {
      compileSdkVersion 28
      defaultConfig {
          applicationId &quot;com.sample.apitest&quot;
          minSdkVersion 16
          targetSdkVersion 28
          versionCode 1
          versionName &quot;1.0&quot;
          testInstrumentationRunner &quot;android.support.test.runner.AndroidJUnitRunner&quot;
      }
      buildTypes {
          release {
              minifyEnabled false
              proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
          }
      }
  }
  
  dependencies {
      implementation fileTree(dir: 'libs', include: ['*.jar'])
      implementation&quot;org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version&quot;
      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'
  }
  </code></pre>
  <hr />
  <p><strong>Django rest framework project</strong></p>
  <p>project/settings.py</p>
  <pre><code>    #...      
  
  INSTALLED_APPS = [
      #...
      'corsheaders',
  ]
  
  MIDDLEWARE = [
      #...
      'corsheaders.middleware.CorsMiddleware',
      'django.middleware.common.CommonMiddleware',
  ]
  
  CORS_ORIGIN_WHITELIST = [
      'http://10.0.2.2:8000'
  ]
  </code></pre>
  <p>API endpoint</p>
  <pre><code>[ Method = GET ] http://127.0.0.1:8000/api/name/
  
      {
        &quot;name&quot;: &quot;myName.&quot;,
      }
  </code></pre>
  <hr />
  <p>android-studio: 3.3.2</p>
  <p>python: 3.7.5</p>
  <p>django-cors-headers: 2.4.0</p>
  <p>djangorestframework: 3.8.2</p>