Java OkHttpClient Can not connect to localhost [closed]

风流意气都作罢 提交于 2020-03-06 11:05:05

问题


When i try to connect my api running on my localhost with OkHttpClient in java. But it throws that error:

java.net.ConnectException: failed to connect to localhost/127.0.0.1 (port 44338) from /127.0.0.1 (port 35986) after 10000ms: isConnected failed: ECONNREFUSED (Connection refused)

I tried to replace "localhost" with my default gateway:192.168.1.1 but still not working.

The code I do request:

 OkHttpClient client = new OkHttpClient();
    RequestBody formBody = new FormBody.Builder()
            .add("Username", "***")
            .add("Password", "****")
            .build();

    Request request = new Request.Builder()
            .url("https://localhost:44338/api/authorize/login")
            .addHeader("Content-Type","application/json")
            .post(formBody)
            .build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(@NotNull Call call, @NotNull IOException e) {
            System.out.println("y" + e.getMessage());
            e.printStackTrace();
        }

        @Override
        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
            System.out.println("ccc :" + response.body().string());
        }
    });

回答1:


It could be because of the url you are setting, you are using localhost instead of the local ipaddress, try it like this

HttpUrl localUrl = HttpUrl.parse("http://YourlocalIPV4Address:44338/api/authorize/login")
Request request = new Request.Builder()
        .url(localUrl)
        .addHeader("Content-Type","application/json")
        .post(formBody)
        .build();

Let me know it it works for you!




回答2:


localhost refers to the device where the app is running, not your development desktop. The emulator acts as a separate device. Unless you are running a web server on your phone, this will not work. You need to use the IP address for your desktop to make a request to the service that is running there. In Windows, you can run ipconfig to find your IP address on your local network.



来源:https://stackoverflow.com/questions/60459255/java-okhttpclient-can-not-connect-to-localhost

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!