天天看点

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就行了