【问题标题】:API works in POSTMAN not in Retrofit androidAPI 在 POSTMAN 中工作而不是在 Retrofit android 中工作
【发布时间】:2019-08-31 17:31:42
【问题描述】:

我正在整合Napster API!这需要不记名访问令牌和带有内容类型的 json。我正在提供所有信息,但我总是收到 400“错误请求”错误。

这是我的改造课。

object RetrofitClientInstance {
private var retrofit: Retrofit? = null

val retrofitInstance: Retrofit
    get() {
        if (retrofit == null) {
            retrofit = Retrofit.Builder()
                .baseUrl(BASE_URL_Secure)
                .client(provideOkHttpClient())
                .addConverterFactory(GsonConverterFactory.create())
                .build()
        }
        return retrofit!!
    }


private fun provideOkHttpClient(): OkHttpClient {

    var logging = HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger {
        override fun log(message: String) {
            Log.d("qweqwe", message)
        }
    })
    logging.setLevel(HttpLoggingInterceptor.Level.BASIC)
    val client = OkHttpClient.Builder()
        .addInterceptor(logging)
        .addNetworkInterceptor(
            object : Interceptor {
                @Throws(IOException::class)
                override fun intercept(chain: Interceptor.Chain): Response {

                    val request = chain.request().newBuilder()
                        .addHeader("Content-Type", "application/json")
                        .build()
                    return chain.proceed(request)
                }
            }
        )

        .build()
    return client
}

这是最喜欢的 API 接口

@POST("/v2.2/me/favorites")
fun setFavorite(
    @Header("Authorization") accessToken: String,
    @Body favorites: JSONObject
): Call<JsonElement>

这是我正在调用的函数..

  private fun setFav(){
    val retrofit  = RetrofitClientInstance.retrofitInstance

    var jsonObject =  JSONObject()
    jsonObject.put("id",track.id)
    var jsonArray = JSONArray()
    jsonArray.put(jsonObject)

    var jsonObject1 = JSONObject()
    jsonObject1.put("favorites", jsonArray)

    val loginAPI = retrofit.create(TrackAPI::class.java)
    val call = loginAPI.setFavorite("Bearer ZTM0NjgyODAtOTY0OS00MTZmLTllYmQtMTMzYWM3M2VhMjkz", jsonObject1)

    call.enqueue(
        object : Callback<JsonElement> {
            override fun onFailure(call: Call<JsonElement>, t: Throwable) {
                t.stackTrace
            }

            override fun onResponse(call: Call<JsonElement>, response: Response<JsonElement>) {

                if (response.isSuccessful) {
                    var jsonElement: JsonElement? = response.body()
                    if (jsonElement != null) {
                        //Rest of the code
                    }
                }
            }
        })
}

这是邮递员的回复。

邮递员图片 -->https://imgur.com/gbz3rAd.jpg

我正在发送 json 对象并接收 json 元素。 请给我解决方案。提前谢谢

【问题讨论】:

  • 当 setFavorite 有 3 个没有默认值时,你如何用 2 个参数调用它?会不会是TrackAPI接口里多了一个setFavorite函数?
  • 我更正了。我正在尝试这种方式,但没有解决方案
  • 有人吗?帮帮我

标签: android rest retrofit


【解决方案1】:

您几乎接近成功。但是使用 Retrofit 向 API 发送参数的方式是错误的。您将org.json.JSONObject 误认为com.google.gson.JsonObject

该 API 需要一个 JSON 主体作为参数,如下所示

{
   "favorites": [
        {
          "id": "alb.54719066"
        }
   ]
}

使用 Retorfit 库,您可以使用 GSONConvertorFactory 将 JSON 转换为 POJO,并将 POJO 转换为 JSON,反之亦然。为了解决您的问题,您只需要更改 API 接口和 Activity/Fragment 中的 JSON Object 类导入。就是这样!

在 API 接口文件中

@POST("/v2.2/me/favorites")
fun setFavorite(
   @Header("Authorization") accessToken: String,
   @Body favorites: JsonObject   /* change from JSONObject to JsonObject */
): Call<JsonElement>

在 Activity/Fragment 内部进行如下更改,

private fun setFav() {

       // code...
   val retrofit  = RetrofitClientInstance.retrofitInstance

   var jsonObject =  JsonObject()   /* change from JSONObject to JsonObject */

   jsonObject.addProperty("id",track.id)   /* change from add() to addProperty() */

   var jsonArray = JsonArray()   /* change from JSONArray to JsonArray */

   jsonArray.add(jsonObject)    /* change from put() to add() */

   var jsonObject1 = JsonObject()   /* change from JSONObject to JsonObject */

   jsonObject1.add("favorites", jsonArray)  /* change from put() to add() */

       // code...
}

对于所有这些更改,您必须使用 import com.google.gson.* 包。

PS:请仔细阅读代码cmets。导入适当的包,使用适当的方法,您就可以测试更改了。

【讨论】:

    猜你喜欢
    • 2017-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    • 2018-06-26
    • 2020-12-14
    • 2020-05-01
    • 1970-01-01
    相关资源
    最近更新 更多