如何从Kotlin的Volley的StringRequest()获取标头和正文

时间:2019-06-12 11:51:30

标签: android kotlin android-volley

为了简单地将身体作为对StringRequest()的响应,您可以编写:

val stringRequest = StringRequest(Request.Method.GET, url,
        Response.Listener<String>  { response -> /*do something with the response*/ },
        Response.ErrorListener     { error -> /*do something with the error*/ }) 

要获取标头,您必须像这样覆盖parseNetworkResponse()

val stringRequest = StringRequest(Request.Method.GET, url,
        Response.Listener<String>{ response -> /*do something with the response*/ },
        Response.ErrorListener{ error -> /*do something with the error*/ }){
    override fun parseNetworkResponse(response:NetworkResponse): Response<String>{
        try{
           // returns some numbers, but not the body:
           val bodyString = getBody().toString()
           // returns some numbers as well:                                
           val responseString = super.parseNetworkResponse(response).toString() 

           // works fine, returns entire header:
           val header = response.headers
           // works fine, returns the header field value of "key":
           //val value = response.headers.get("key")        

           val all = header.toString() + bodyString  

           return (Response.success(all, HttpHeaderParser.parseCacheHeaders(response)))

        }catch (e: Exception){
           return Response.error(ParseError(e))
       }
    }
}

但是,当我覆盖parseNetworkResponse()时,即使我呼叫super.parseNetworkResponse()getBody(),身体的反应似乎也消失了。

我想从一个StringRequest()中获取标头和正文。

此处已针对Java描述了如何将标头作为JSON对象添加到JSON请求响应中:Getting headers from a response in volley

在科特林parseNetworkResponse()中,外观如下:

override fun parseNetworkResponse(response:NetworkResponse): Response<JSONObject>{
    try{
        val charsetString: String = HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET);
        val charset: Charset = charset(charsetString)
        val jsonString = String(response.data, charset)
        val jsonResponse = JSONObject(jsonString)
        jsonResponse.put("headers", JSONObject(response.headers))

        return Response.success(jsonResponse, HttpHeaderParser.parseCacheHeaders(response))

    }catch (e: JSONException){
        return Response.error(ParseError(e))
  }
}

效果很好。

因此,我认为也可以同时从StringRequest()获得这两者。

我做错了什么?

0 个答案:

没有答案