java okclient,Java OkHttpClient无法连接到本地主机

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());

}

});

解决方案

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!