英文:
How to interface with an API from android?
问题
我构建了一个Android应用程序,并建立了一个相应的Node.js后端,用于存储来自该应用程序的数据。我已经创建了一些API端点,以及用于在MongoDB中保存和检索数据的方法。
我了解如何从Java/Android发出HTTPS请求,但我不确定理想的设置和结构应该是什么样的。创建一个新的用于API相关事物的包是最佳实践吗?就像这样的一个包:
API包
包含GET请求的类
包含POST请求的类
这些类可能包含像这样的方法:
public static String getItem(int item_id) {
//HTTPS样板代码
//发出HTTPS GET请求并处理数据
返回结果;
或者是创建一个处理和发出HTTPS请求的类,然后在单独的一个类中实现所有所需的API方法,哪种方式是最佳做法呢?
英文:
I built an android app and have built a corresponding node.js back-end to store data from it. I've got some API end-points created along with methods to save and retrieve data from a MongoDB.
I understand how to make https requests from java/android, but I'm not sure how things should ideally be set-up and structed. Is it best practice to create a new package for api related things? Like for example, a package like:
API Package
Class containing GET requests
Class containing POST requests
These classes might contain methods like:
public static String getItem(int item_id) {
//HTTPS boiler plate
//HTTPS GET request and process data
return result;
Or is it best to create a class to handle and make HTTPS requests and then implement all of the required API methods in a single, separate class?
答案1
得分: 2
有一些流行的库可以供你参考,比如Retrofit或Android Volley。我建议你不要自己编写与后端通信的代码,因为诸如解析JSON数据之类的事情不应该手动完成,随着项目的增长,一切都会变得难以管理。
为了组织代码,这取决于个人偏好。我个人使用Retrofit,所以我将所有的网络请求都保留在一个接口中。例如:
interface APIs {
@GET("api/user")
Call<Users> getUsers();
@GET("api/comment")
Call<Comments> getComments();
@GET("api/photos")
Call<Photos> getPhotos();
}
但如果你想了解如何进行良好的设置和结构化,我建议你阅读关于Android架构组件和Clean Code架构的内容,其中代码逻辑被分开并以可管理的方式进行分组。
英文:
There are several popular libraries out there that you can check it out like Retrofit or Android Volley. I recommend you not to write the code to make requests to the backend yourself because things like parsing JSON data shouldn't be done manually as everything will be hard to manage when your project grows.
To structure the code, it depends on personal preference. I personally use Retrofit so I keep all network requests in an interface. For example:
interface APIs {
@GET("api/user")
Call<Users> getUsers();
@GET("api/comment")
Call<Comments> getComments();
@GET("api/photos")
Call<Photos> getPhotos();
}
But if you want to learn how things should be set-up and structured nicely, I suggest you read about the Android architecture component and Clean Code architecture where code logics are kept separately and grouped in a manageable way.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论