gpt4 book ai didi

java - 如何使用 HttpUrlConnection 在 Android 中构建 REST 客户端

转载 作者:行者123 更新时间:2023-11-29 04:49:37 25 4
gpt4 key购买 nike

我想构建一个使用一些 REST API 的 Android 应用。

我正在使用 HttpURLConnection 进行基本身份验证并获取/放置一些数据,但我觉得我做错了。我有两个类 ConnectionPUTConnectionGET 我为每个请求调用它们,因为每个 HttpURLConnection 实例都用于发出单个请求。

使用 HttpURLConnection 构建 Android REST 客户端的正确方法是什么?

最佳答案

这是在 Android 中使用 HttpUrlConnection 调用 Http GET 的示例代码。

  URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL("your-url-here");

urlConnection = (HttpURLConnection) url
.openConnection();

InputStream in = urlConnection.getInputStream();

InputStreamReader isw = new InputStreamReader(in);

int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
System.out.print(current);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();


}
}

但我强烈建议不要重新发明轮子来为您的 Android 应用程序创建 REST 客户端,而是尝试使用适合网络的 Retrofit 和 Volley 等适应性强且可靠的库。

它们高度可靠且经过测试,并删除了您必须为网络通信编写的所有样板代码。

想了解更多信息,我建议你研究下面这篇关于 Retrofit 和 Volley 的文章

Android - Using Volley for Networking

Android -Using Retrofit for Networking

关于java - 如何使用 HttpUrlConnection 在 Android 中构建 REST 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35886537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com