在Android

时间:2018-04-12 19:27:21

标签: android retrofit

我在我的localhost中运行的服务器中包含我想要在我的Android应用程序中显示的数据库中的一些信息,我使用改造库来执行此操作,但我只收到此消息:< / p>

  

从API加载错误

这是我的RetrofitClient:

公共类RetrofitClient {

private static Retrofit retrofit = null;

public static Retrofit getClient(String baseUrl) {
    if (retrofit==null) {
        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
}

}

以下是使用我的GET方法的类:

public interface SOService {

    @GET("stocks/")
Call<List<Stock>> getStocks();

}

这是我的班级与网址以及如何连接:

public class ApiUtils {

    public static final String BASE_URL = "http://127.0.0.1:8000";

    public static SOService getSOService() {
        return RetrofitClient.getClient(BASE_URL).create(SOService.class);
    }
}

在这里,我最终尝试获取信息:

public class RegisterActivity extends AppCompatActivity {

    private Button registerButton;
    private SOService mService;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        mService = ApiUtils.getSOService();

        registerButton = findViewById(R.id.register_button);
        registerButton.setOnClickListener(v -> loadAnswers());
    }

    public void loadAnswers() {

        System.out.println("Entro aquí");
        mService.getStocks().enqueue(new Callback<List<Stock>>() {
        @Override
        public void onResponse(Call<List<Stock>> call, Response<List<Stock>> response) {
            if(response.isSuccessful()) {

                System.out.println("Te lo imprimo");
                System.out.println(response.body().toString());
                Log.d("MainActivity", "posts loaded from API");
            }else {
                int statusCode  = response.code();
                // handle request errors depending on status code
            }
        }

        @Override
        public void onFailure(Call<List<Stock>> call, Throwable t) {
            Log.d("MainActivity", "error loading from API");

        }
    });
    }
}

我是这样的课程:

public class Stock {

    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("ticker")
    @Expose
    private String ticker;
    @SerializedName("open")
    @Expose
    private Double open;
    @SerializedName("close")
    @Expose
    private Double close;
    @SerializedName("volume")
    @Expose
    private Integer volume;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getTicker() {
        return ticker;
    }

    public void setTicker(String ticker) {
        this.ticker = ticker;
    }

    public Double getOpen() {
        return open;
    }

    public void setOpen(Double open) {
        this.open = open;
    }

    public Double getClose() {
        return close;
    }

    public void setClose(Double close) {
        this.close = close;
    }

    public Integer getVolume() {
        return volume;
    }

    public void setVolume(Integer volume) {
        this.volume = volume;
    }

}

知道为什么它有效吗?

这是我得到的错误:

  

W / System.err:java.net.ConnectException:无法连接   /127.0.0.1:8000                     在okhttp3.internal.connection.RealConnection.connectSocket(RealConnection.java:242)   W / System.err:at   okhttp3.internal.connection.RealConnection.connect(RealConnection.java:160)                     在okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:257)                     在okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:135)                     在okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:114)                     在okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)   W / System.err:at   okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)                     在okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)   W / System.err:at   okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)                     在okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)                     在okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)                     在okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)                     在okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)                     在okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126)                     在okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)                     在okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)   W / System.err:at   okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)                     在okhttp3.RealCall $ AsyncCall.execute(RealCall.java:147)                     在okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)                     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)                     at java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:636)                     at java.lang.Thread.run(Thread.java:764)W / System.err:引起:java.net.ConnectException:连接失败   10000ms后从/127.0.0.1(端口42532)到/127.0.0.1(端口8000):   isConnected失败:ECONNREFUSED(拒绝连接)                     在libcore.io.IoBridge.isConnected(IoBridge.java:273)                     在libcore.io.IoBridge.connectErrno(IoBridge.java:188)                     在libcore.io.IoBridge.connect(IoBridge.java:130)                     在java.net.PlainSocketImpl.socketConnect(PlainSocketImpl.java:129)                     at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:356)                     at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)                     at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)                     在java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356)   W / System.err:at java.net.Socket.connect(Socket.java:616)                     在okhttp3.internal.platform.AndroidPlatform.connectSocket(AndroidPlatform.java:71)                     在okhttp3.internal.connection.RealConnection.connectSocket(RealConnection.java:240)                     ......还有21个                 引起:android.system.ErrnoException:isConnected失败:ECONNREFUSED(连接被拒绝)W / System.err:at   libcore.io.IoBridge.isConnected(IoBridge.java:262)                     ......还有31个

1 个答案:

答案 0 :(得分:1)

你应该尝试检索这样的对象列表:

public interface SOService {

    @GET("stocks/")
    Call<List<Stock>> getStocks();

}

mService.getStocks().enqueue(new Callback<List<Stock>>() {
            @Override
            public void onResponse(Call<List<Stock>> call, Response<List<Stock>> response) {
                if(response.isSuccessful()) {

                    System.out.println("Te lo imprimo");
                    System.out.println(response.body().toString());
                    Log.d("MainActivity", "posts loaded from API");
                }else {
                    int statusCode  = response.code();
                    // handle request errors depending on status code
                }
            }

            @Override
            public void onFailure(Call<List<Stock>> call, Throwable t) {
                Log.d("MainActivity", "error loading from API");

            }
        });

修改

您尝试连接到计算机上的本地服务器,但是通过模拟器。模拟器无法连接到此服务器。检查此answer。您正在使用的本地URL将通过改造用于在您的PHONE(仿真器)上本地识别端口和地址。这就是为什么你无法联系的原因。该地址的手机上没有服务器。您需要输入您的PC IP地址才能工作:)