【问题标题】:Retrofit Android POST request with Header, Body, Path and Query使用 Header、Body、Path 和 Query 改造 Android POST 请求
【发布时间】:2022-07-25 23:21:28
【问题描述】:

我需要通过 Android Kotlin 代码做一个 Retrofit POST 请求,格式如下:

[End Url]/api/customers/1/venues/55/abcfiles/sasfordownload?licenseid=01234567890&ispreproduction=true

标题:

授权 -> Bearer someToken

主体:

{ "some_field" : {"55" : "29"}}

--

回应:

“一些字符串值”

POST 请求:

@POST("customers/{customers}/venues/{venues}/abcfiles/sasfordownload")
fun makeRequestForfileUrl(
    @HeaderMap token: Map<String, String>,
    @Path("customers")
    customers: Int,
    @Path("venues")
    venues: Int,
    @Query("licenseid")
    licenceId: String,
    @Query("ispreproduction")
    ispreproduction: Boolean,
    @Body
    body: JSONObject
): Call<String>

改造建造者:

fun requestApi(mContext: Context): ApiInterface {
return Retrofit.Builder()
        .baseUrl(apiUrl)
        .addConverterFactory(GsonConverterFactory.create())
        .client(
            OkHttpClient.Builder()
                .addInterceptor(NetworkConnectionInterceptor(mContext))
                .addInterceptor(httpLoggingInterceptor)
                .build()
        )
        .build()
        .create(ApiInterface::class.java)
}

改造 API 请求:

val headerMap = HashMap<String, String>()
    headerMap["Authorization"] = "Bearer $fetchedToken"
    headerMap["Content-Type"] = "application/json"

val apiInterface =
        ServiceGenerator.requestApi().makeRequestForfileUrl(
            headerMap,
            customerId,
            venueId,
            licenceId,
            true,
            JSONObject("{\"some_field\" : { \"55\" : \"29\" }}")
        )

获取上述请求的响应代码 500。

响应{protocol=h2, code=500, message=, url=[End Url]/api/customers/1/venues/55/abcfiles/sasfordownload?licenseid=0123456789&ispreproduction=true} 响应正文 -> null

API 请求正在 Postman 上工作。

【问题讨论】:

  • 请分享您的日志,以便人们正确理解您的问题。

标签: android api kotlin retrofit2


【解决方案1】:

org.json.JSONObject 更改为com.google.gson.JsonObject 后的工作

@POST("customers/{customers}/venues/{venues}/abcfiles/sasfordownload")
fun makeRequestForfileUrl(
@HeaderMap token: Map<String, String>,
@Path("customers")
customers: Int,
@Path("venues")
venues: Int,
@Query("licenseid")
licenceId: String,
@Query("ispreproduction")
ispreproduction: Boolean,
@Body
body: JsonObject //<- here changed org.json.JSONObject to com.google.gson.JsonObject
): Call<String>

val apiInterface =
    ServiceGenerator.requestApi().makeRequestForfileUrl(
        headerMap,
        customerId,
        venueId,
        licenceId,
        true,
        JsonObject) //<- "{\"some_field\" : { \"55\" : \"29\" }}" in this format 
    )

不知道org.json.JSONObjectcom.google.gson.JsonObject

有什么区别

但使用 com.google.gson.JsonObject

如果有人知道差异,请在此处添加。

【讨论】:

    猜你喜欢
    • 2022-01-04
    • 1970-01-01
    • 2021-04-10
    • 2018-07-24
    • 1970-01-01
    • 1970-01-01
    • 2018-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多