【发布时间】:2019-11-21 15:12:08
【问题描述】:
我想通过 Java 和 Kotlin 发出简单的 Volley POST 请求。我在我的应用程序中使用这两种语言,所以我尽量使用这两种语言。 我在 Kotlin 中使用以下 VolleyClass 完成了 this 教程:
class WolfRequest(val url: String, val 结果:(JSONObject)-> 单位, val 错误:(字符串)-> 单位){
fun POST(vararg params: Pair<String, Any>) {
// HashMap to pass arguments to Volley
val hashMap = HashMap<String, String>()
params.forEach {
// Convert all Any type to String and add to HashMap
hashMap[it.first] = it.second.toString()
}
// Make the Http Request
makeRequest(Request.Method.POST, hashMap)
}
private fun makeRequest(method: Int, params: HashMap<String, String>) {
// Creating a StringRequest
val req = object : StringRequest(method, url, { res ->
// Creating JSON object from the response string
// and passing it to result: (JSONObject) -> Unit function
result(JSONObject(res.toString().trim()))
}, { volleyError ->
// Getting error message and passing it
// to val error: (String) -> Unit function
error(volleyError.message!!)
}) {
// Overriding getParams() to pass our parameters
override fun getParams(): MutableMap<String, String> {
return params
}
}
// Adding request to the queue
volley.add(req)
}
// For using Volley RequestQueue as a singleton
// call WolfRequest.init(applicationContext) in
// app's Application class
companion object {
var context: Context? = null
val volley: RequestQueue by lazy {
Volley.newRequestQueue(context
?: throw NullPointerException(" Initialize WolfRequest in application class"))
}
fun init(context: Context) {
this.context = context
}
}
}
我正在尝试从 Java.Class 访问此代码以进行 POST Reuqest:
WolfRequest.Companion.init(getApplicationContext());
HashMap <String, String> params = new HashMap <> ();
params.put("id", "123");
new WolfRequest(config.PING_EVENTS,*new WolfRequest()*
{
public void response(JSONObject response) {
Log.e("Ping","PING");
}
public void error(String error) {
Log.e("Ping",error);
}
}).POST(params);
这里给我一个错误 (new WolfRequest()) 说:不能从 final "...wolfrequest.kt" 继承
我真的不明白错误,这里有什么问题?
谢谢
【问题讨论】:
标签: java android kotlin android-volley