如何解决Android中使用Kotlin的简单HTTP请求示例
我是Kotlin的Android开发新手,我正在努力寻找有关如何创建具有最佳最新实践的简单GET和POST请求的有用文档。我来自Angular开发,在那里我们使用了RxJS进行反应式开发。
通常我会创建一个包含所有请求功能的服务文件,然后在任何组件中使用此服务并订阅可观察对象。
您将如何在Android中执行此操作?是否有一个必须创建的事物的良好的入门示例。乍一看,一切看起来都如此复杂和过度设计
解决方法
您曾经获得的最佳实践就是通过网络通话的基础知识并使用Android Studio创建一些演示应用程序。
如果要单击“开始”,请按照本教程进行操作
在Kotlin中进行简单的网络呼叫
https://www.androidhire.com/retrofit-tutorial-in-kotlin/
此外,我想建议请为GET和POST请求创建一些演示应用程序,然后将这些示例合并到您的项目中。
,您可以使用类似的内容:
internal inner class RequestTask : AsyncTask<String?,String?,String?>() {
override fun doInBackground(vararg params: String?): String? {
val httpclient: HttpClient = DefaultHttpClient()
val response: HttpResponse
var responseString: String? = null
try {
response = httpclient.execute(HttpGet(uri[0]))
val statusLine = response.statusLine
if (statusLine.statusCode == HttpStatus.SC_OK) {
val out = ByteArrayOutputStream()
response.entity.writeTo(out)
responseString = out.toString()
out.close()
} else {
//Closes the connection.
response.entity.content.close()
throw IOException(statusLine.reasonPhrase)
}
} catch (e: ClientProtocolException) {
//TODO Handle problems..
} catch (e: IOException) {
//TODO Handle problems..
}
return responseString
}
override fun onPostExecute(result: String?) {
super.onPostExecute(result)
//Do anything with response..
}
}
并致电:
RequestTask().execute("https://v6.exchangerate-api.com/v6/")
sdk 23中不再支持 HttpClient
。您必须使用URLConnection
或降级到sdk 22(compile 'com.android.support:appcompat-v7:22.2.0'
)
如果您需要sdk 23,请将其添加到gradle:
android {
useLibrary 'org.apache.http.legacy'
}
您还可以尝试下载HttpClient.jar并将其直接包含到您的项目中,或改为使用OkHttp
,为方便起见,我建议您使用@client.event
async def on_message(message):
global Hangman,guessed,tries,guessed_letters,channel,word,word_completion,guessed_words
if message.content.startswith('.hm'):
Hangman = True
print("hangman started")
channel = message.channel
word = get_word()
word_completion = "_" * len(word)
guessed = False
guessed_letters = []
guessed_words = []
tries = 6
await channel.send("Let's play hangman")
await channel.send(display_hangman(tries))
await channel.send(word_completion)
elif message.content.startswith('.hm quit'):
Hangman = False
if Hangman:
print(str(guessed) + str(tries))
if not guessed and tries > 0:
def check(m):
if any(c.isalpha() for c in m.content) and len(str(m)) == 1:
return m.content == message
print('Running')
guess = await client.wait_for('message',check=check)
print(str(guess))
if len(str(guess)) == 1:
if guess in guessed_letters:
await channel.send("You already guessed the letter",guess)
elif guess not in word:
await channel.send(guess,"is not in the word.")
tries -= 1
guessed_letters.append(guess)
else:
await channel.send("Good job,",guess,"is in the word!")
guessed_letters.append(guess)
word_as_list = list(word_completion)
indices = [i for i,letter in enumerate(word) if letter == guess]
for index in indices:
word_as_list[index] = guess
word_completion = "".join(word_as_list)
if "_" not in word_completion:
guessed = True
elif len(guess) == len(word) and guess.isalpha():
if guess in guessed_words:
await channel.send("You already guessed the word",guess)
elif guess != word:
await channel.send(guess,"is not the word.")
tries -= 1
guessed_words.append(guess)
else:
guessed = True
word_completion = word
else:
await channel.send("Not a valid guess.")
await channel.send(display_hangman(tries))
await channel.send(word_completion)
if guessed:
await channel.send("Congrats,you guessed the word! You win!")
else:
await channel.send("Sorry,you ran out of tries. The word was " + word + ". Maybe next time!")
或Fuel
库的官方推荐,并且使用流行的Json / ProtoBuf库,它还具有将响应反序列化为对象的绑定。
燃油示例:
OkHttp
OkHttp 示例:
// Coroutines way:
// both are equivalent
val (request,response,result) = Fuel.get("https://httpbin.org/ip").awaitStringResponseResult()
val (request,result) = "https://httpbin.org/ip".httpGet().awaitStringResponseResult()
// process the response further:
result.fold(
{ data -> println(data) /* "{"origin":"127.0.0.1"}" */ },{ error -> println("An error of type ${error.exception} happened: ${error.message}") }
)
// Or coroutines way + no callback style:
try {
println(Fuel.get("https://httpbin.org/ip").awaitString()) // "{"origin":"127.0.0.1"}"
} catch(exception: Exception) {
println("A network request exception was thrown: ${exception.message}")
}
// Or non-coroutine way / callback style:
val httpAsync = "https://httpbin.org/get"
.httpGet()
.responseString { request,result ->
when (result) {
is Result.Failure -> {
val ex = result.getException()
println(ex)
}
is Result.Success -> {
val data = result.get()
println(data)
}
}
}
httpAsync.join()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。