首页 > 解决方案 > 来自 python 的 Kotlin 等效 request.post() 是什么?

问题描述

所以我正在尝试使用来自网站的 API,但为了使用它,我必须发送我的登录信息。该文档向我展示了一个有关如何登录的 python 示例。

R = requests.post('http://nova.astrometry.net/api/login', data={'request-json': 
json.dumps({"apikey": "XXXXXXXX"})})
print(R.text)

那么上述代码的 Kotlin 等价物是什么?在网站文档中它指出

“请注意 request-json=VALUE:我们发送的不是原始 JSON,而是发送 JSON 编码的字符串,就好像它是一个名为 request-json 的文本字段一样。”

我曾尝试使用Android Volley,但我不完全确定如何使用它。

private fun plateSolve(){
    val json=JSONObject(map).toString()
    Log.d(TAG,"URL:$url")
    Log.d(TAG,"Hashmap:$json")

    JSONObject(map).toString()

    val jsonObjectRequest = JsonObjectRequest(
        Request.Method.POST, url, null,
        { response ->

            try {
                Log.d(TAG,"POST Response: %s".format(response.toString()))
            }catch (e:Exception){
                Log.d(TAG,"Exception: $e")

            }

        },
        { error ->
            // TODO: Handle error
            Log.d(TAG,"There Was an Error")
            error.stackTraceToString()
        }
    )

    // Access the RequestQueue through your singleton class.
    VolleySingleton.instance?.addToRequestQueue(jsonObjectRequest)

  }

提前致谢

标签: androidkotlinandroid-volley

解决方案


不建议再为 android 使用 volley 请使用改造作为其谷歌推荐的库,你的问题的答案太大了,所以我会写一些检查点来做,而且我已经分享了一个简单的工作示例,用于改造我自己的一个项目在github上,希望对你有帮助

改造链接 - https://square.github.io/retrofit/

  1. 在 gradle 中插入库文件
  2. 创建响应类
  3. 创建改造 api 类 4.使用 api 调用创建接口类

带有应用程序的 Github 项目使用改进的 api 调用 https://github.com/zaidzak9/NewsApp


推荐阅读