如何在安卓中与API进行交互?

huangapple go评论74阅读模式
英文:

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

有一些流行的库可以供你参考,比如RetrofitAndroid 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(&quot;api/user&quot;)
    Call&lt;Users&gt; getUsers();

    @GET(&quot;api/comment&quot;)
    Call&lt;Comments&gt; getComments();

    @GET(&quot;api/photos&quot;)
    Call&lt;Photos&gt; 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.

huangapple
  • 本文由 发表于 2020年9月15日 07:45:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/63893169.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定