【问题标题】:Android - Failed to connect to rest API - Bad RequestAndroid - 无法连接到 REST API - 错误请求
【发布时间】:2020-06-08 16:02:46
【问题描述】:

我正在尝试将我的 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://:5000/energy/api/,但收到错误的请求消息。

>   D/OkHttp: <-- 400 Bad Request

有什么帮助吗?

【问题讨论】:

  • Android 已弃用明文 http 流量。链接(stackoverflow.com/questions/45940861/…) 到相关帖子,请确保您不是该帖子的受害者。如果是,您最终会遇到这样的 IOException -“..Exception: IOException java.io.IOException: Cleartext HTTP traffic to * not allowed”
  • @Som 是的,这对我来说以前是个问题,但我找到了那个确切的帖子并把它改正了。所以现在不是问题了

标签: android api kotlin localhost retrofit


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    如果您使用的基本 URL 是 http://localhost:5000/api/&lt;PC IP&gt;,则在模拟器上而不是在实际设备上运行您的应用程序,因为所有代码和 api 都在您的本地服务器中运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-10
      • 2019-02-24
      • 1970-01-01
      • 2013-05-09
      • 2014-05-04
      • 2018-02-03
      • 1970-01-01
      相关资源
      最近更新 更多