我找到了一个关于如何获取 url 的 youtube 视频,但我需要发布一个 REST api。我不确定该怎么做。
我试着在这里四处看看,但大部分都是 java。
fun fetchJson() {
println ("attempting to fetch JSON")
val url = "https://utgapi.shift4test.com/api/rest/v1/transactions/sale"
val request = Request.Builder().url(url).build()
val client = OkHttpClient()
client.newCall(request).enqueue(object: Callback {
override fun onResponse(call: Call?, response: Response?) {
val body = response?.body()?.string()
println(body)
println("try and get json api working there was an error")
}
override fun onFailure(call: Call, e: IOException) {
println("failed to execute request")
}
使用 GET 我只是收到一个错误,因为我没有执行 POST 请求。
最佳答案
在这里找到了一些东西 https://stackoverflow.com/a/29795501/5182150 将其转换为 Kotlin 就像
private val client = OkHttpClient();
fun run() throws Exception {
val formBody = FormEncodingBuilder()
.add("search", "Jurassic Park")
.build() as RequestBody;
val request = new Request.Builder()
.url("https://en.wikipedia.org/w/index.php")
.post(formBody)
.build();
val response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
这应该是要点。当工作室向您发出警告时,您可以处理可为空的问题。 另一个提示是您也可以使用 Retrofit,它可以使用 OkHTTP 进行网络调用。您可以在此处找到更多关于改造的信息 https://square.github.io/retrofit/这里有一个很好的教程 https://medium.com/@prakash_pun/retrofit-a-simple-android-tutorial-48437e4e5a23
关于android - 将 Json 和 header 发布到 REST api KOTLIN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56739284/