簡體   English   中英

我的應用無法發送GET,OkHttp

[英]My app can't send a GET, OkHttp

我有一個奇怪的問題。
我在localhost:8080有服務,並且一切配置都很好,我可以使用Android設備(真實的,不是模擬器)在瀏覽器中打開此服務。 我認為我的代碼有問題。

但是在應用程序中,我得到了java.net.ConnectException: Failed to connect to localhost/127.0.0.1:8080

這是我的代碼:

private void sendGET() {

        OkHttpClient.Builder client = new OkHttpClient.Builder();
        client.authenticator(new Authenticator() {
            @Override
            public Request authenticate(Route route, Response response) throws IOException {
                String credential = Credentials.basic("admin", "admin");
                return response.request().newBuilder().header("Authorization", credential).build();
            }
        });

        Request request = new Request.Builder()
                .url("http://localhost:8080/users")
                .build();

        client.build().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.w("http", e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.w("http", response.body().string());
            }
        });

    }

這里有什么問題?

localhost如何映射到實際IP地址可能存在問題。 嘗試使用您的實際IP地址:

Request request = new Request.Builder()
            .url("http://192.168.0.1:8080/users")  // for example
            .build();

以上假設IP地址為192.168.0.1

要查找您的IP地址,請在Windows上鍵入ipconfig或在Linux上鍵入ifconfig

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM