首页 > 解决方案 > Android - 无法连接到 REST API - 错误请求

问题描述

我正在尝试将我的 android 应用程序与在我的 PC 上运行的 API 连接起来。

我正在我的实际手机上测试该应用程序。基本 URL 是http://localhost:5000/api/

object RequestManager {
    val interceptor = HttpLoggingInterceptor()
    val client = OkHttpClient.Builder().addInterceptor(interceptor).build()


    init {
        //TODO must be None at live
        interceptor.level = HttpLoggingInterceptor.Level.BODY
    }


    val retrofit = Retrofit.Builder()
        .baseUrl("http://localhost:5000/energy/api/")
        .addConverterFactory(GsonConverterFactory.create())
        .client(client)
        .build()

    val service = retrofit.create(Api::class.java)

}

我尝试使用 http://< myIP >:5000/energy/api/ 但收到错误的请求消息。

>   D/OkHttp: <-- 400 Bad Request

有什么帮助吗?

标签: androidapikotlinlocalhostretrofit

解决方案


尝试使用ngrok。当您插入 localhost 和端口时,它可以解决您的问题,它为您提供了一个可以使用的 URL。


推荐阅读