【问题标题】:How to add a header to a request from volley library [duplicate]如何将标头添加到来自 volley 库的请求中[重复]
【发布时间】:2020-09-13 12:03:38
【问题描述】:

我正在使用 kotlin 开发一个 android 应用程序,在这条路上我想使用一个请求来响应来自 restfull 服务器的... 现在看看我从服务器请求它的代码及其真实,但我不知道如何将标头的参数添加到我的请求中

fun sendCode(){
    val URL = "https://RestfulSms.com/api/MessageSend"
    val body : JSONObject = JSONObject()
    val header : JSONObject = JSONObject()
    body.put("Messages",messageText )
    body.put("MobileNumbers",PhoneNumber )
    body.put("LineNumber","***********")
    body.put("SendDateTime","")
    body.put("CanContinueInCaseOfError","false")

    val request :JsonObjectRequest = JsonObjectRequest(Request.Method.POST,
        URL,
        body,
        Response.Listener<JSONObject> { response ->
            Log.e(tag, response.toString())
        },
        Response.ErrorListener{ error ->
            Log.e(tag, error.message )
        })


    //request.headers.put("Content-Type","application/json")
    header.put("x-sms-ir-secure-token",tokenKey)
    queue.getCache().clear();
    queue.add(request)
}

【问题讨论】:

标签: android rest android-studio kotlin android-volley


【解决方案1】:

在提出此类问题之前,请先搜索文档和其他帖子。 Volley 是一个标准库,并提供了很好的文档。

查看这篇文章 https://stackoverflow.com/a/44049327/4491971

【讨论】:

  • 我在此之前搜索并查看了文档和其他帖子,但我与其他情况略有不同......其他人使用 stringRequest 是的,您可以覆盖 getHeaders 函数并替换您的自定义标头,但我使用 JsonObjectRequest用于获取我的信息,它没有任何 getHeaders 函数可以覆盖 ...
  • @arashforus - 我能理解使用 JsonObjectRequest 的必要性吗?如果服务器期望这样,我们可以在请求中应用相应的内容类型,而不是这样做,对吗?
【解决方案2】:

我发现了我的问题,解决方法如下

我只是将 object 替换为 JsonObjectRequest,然后使用覆盖 getHeaders 函数

            val request :JsonObjectRequest = object : JsonObjectRequest(Request.Method.POST,
            URL,
            body,
            Response.Listener<JSONObject> { response ->
                Log.e(tag, response.toString())
            },
            Response.ErrorListener{ error ->
                Log.e(tag, error.message )
            }) {

            @Throws(AuthFailureError::class)
            override fun getHeaders(): Map<String, String> {
                val headers = HashMap<String, String>()
                headers.put("Content-Type", "application/json");
                headers["x-sms-ir-secure-token"] = tokenKey
                return headers
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-14
    • 2016-11-14
    • 1970-01-01
    • 1970-01-01
    • 2013-03-27
    相关资源
    最近更新 更多