天天看點

android java.net.ConnectException: Failed to connect to localhost/127.0.0.1:xxx

今天在進行Android學習的時候遇到了這個問題

2021-08-12 16:21:17.382 4308-4434/com.example.myandroidtest E/su: Failed to connect to localhost/127.0.0.1:18813
    java.net.ConnectException: Failed to connect to localhost/127.0.0.1:18813
        at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:147)
        at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:116)
        at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:186)
        at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:128)
        at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:97)
        at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:289)
        at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:232)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:465)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:131)
        at com.example.myandroidtest.util.HttpUrlConnectionTest.postTest(HttpUrlConnectionTest.java:46)
        at com.example.myandroidtest.PicDownloadActivity$DownlaodTask.doInBackground(PicDownloadActivity.java:80)
        at com.example.myandroidtest.PicDownloadActivity$DownlaodTask.doInBackground(PicDownloadActivity.java:70)
        at android.os.AsyncTask$3.call(AsyncTask.java:378)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:289)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:919)
           

首先我的環境是usb真機運作,寫了一個HttpURLConnection測試用例,請求位址是本地電腦跑的一個服務,可能是之前Java代碼寫習慣了,測試接口都喜歡用localhost和127.0.0.0.1,結果這次是在手機上運作,發現位址怎麼都連不上,報了上邊那個錯,以為是自己代碼寫得有問題,各種姿勢都試過了還是不行。後來拿着手機點了幾下,才驚覺手機和電腦沒在同一個區域網路,手機的localhost也不是電腦的localhost。。

我的url是這個:

電腦ip是192.168.1.161,

首先手機和電腦要在同一個區域網路,然後把url換成電腦的ip就行了