有许多很好的答案已经回答了这个问题,但是自那些答案发布以来,许多优秀的库已经出现。本文旨在作为新手指南。
我将涵盖执行网络操作的几种用例和每种用例的一两个解决方案。
REST over HTTP
通常使用JSON,但也可以是XML或其他格式。
完整API访问
假设您正在编写一个应用程序,让用户跟踪股票价格、利率和货币汇率。您找到了一个类似于以下内容的JSON API:
http://api.example.com/stocks // ResponseWrapper<String> object containing a
// list of strings with ticker symbols
http://api.example.com/stocks/$symbol // Stock object
http://api.example.com/stocks/$symbol/prices // PriceHistory<Stock> object
http://api.example.com/currencies // ResponseWrapper<String> object containing a
// list of currency abbreviation
http://api.example.com/currencies/$currency // Currency object
http://api.example.com/currencies/$id1/values/$id2 // PriceHistory<Currency> object comparing the prices
// of the first currency (id1) to the second (id2)
Retrofit from Square
这是一个优秀的API选择,适用于具有多个端点的API,并允许您声明REST端点,而不必像其他库(如Amazon Ion Java或Volley(网站:Retrofit)一样单独编写代码。
如何将其与财务API一起使用?
文件build.gradle
将以下行添加到您的模块级别的build.gradle文件中:
implementation 'com.squareup.retrofit2:retrofit:2.3.0' // Retrofit library, current as of September 21, 2017
implementation 'com.squareup.retrofit2:converter-gson:2.3.0' // Gson serialization and deserialization support for retrofit, version must match retrofit version
文件 FinancesApi.java
public interface FinancesApi {
@GET("stocks")
Call<ResponseWrapper<String>> listStocks();
@GET("stocks/{symbol}")
Call<Stock> getStock(@Path("symbol")String tickerSymbol);
@GET("stocks/{symbol}/prices")
Call<PriceHistory<Stock>> getPriceHistory(@Path("symbol")String tickerSymbol);
@GET("currencies")
Call<ResponseWrapper<String>> listCurrencies();
@GET("currencies/{symbol}")
Call<Currency> getCurrency(@Path("symbol")String currencySymbol);
@GET("currencies/{symbol}/values/{compare_symbol}")
Call<PriceHistory<Currency>> getComparativeHistory(@Path("symbol")String currency, @Path("compare_symbol")String currencyToPriceAgainst);
}
类
FinancesApiBuilder,编号为
。
public class FinancesApiBuilder {
public static FinancesApi build(String baseUrl){
return new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(FinancesApi.class);
}
}
类 FinancesFragment 代码片段
FinancesApi api = FinancesApiBuilder.build("http://api.example.com/");
api.getStock("INTC").enqueue(new Callback<Stock>(){
@Override
public void onResponse(Call<Stock> stockCall, Response<Stock> stockResponse){
Stock stock = stockCall.body();
}
@Override
public void onResponse(Call<Stock> stockCall, Throwable t){
}
}
如果您的API需要API密钥或其他标头(例如用户令牌等)发送,Retrofit可以轻松实现此目的(有关详细信息,请参见
这个很棒的答案到
在Retrofit中添加标头参数)。
一次性REST API访问
假设您正在构建一个“心情天气”应用程序,该应用程序查找用户的GPS位置并检查该地区的当前温度,并告诉他们心情。这种类型的应用程序不需要声明API端点;它只需要能够访问一个API端点。
Ion
这是一种非常适合这种访问的库。
请阅读
msysmilu的好答案到
如何修复“android.os.NetworkOnMainThreadException”?。
通过HTTP加载图像
Volley
虽然Volley也可用于REST API,但由于需要更复杂的设置,我更喜欢使用如上所述的Retrofit。
假设您正在构建一款社交网络应用,并希望加载朋友的个人资料图片。
build.gradle文件
将以下行添加到您的模块级别的build.gradle文件中:
implementation 'com.android.volley:volley:1.0.0'
文件 ImageFetch.java
Volley需要比Retrofit更多的设置。您需要创建一个类来设置RequestQueue、ImageLoader和ImageCache,但这并不太困难:
public class ImageFetch {
private static ImageLoader imageLoader = null;
private static RequestQueue imageQueue = null;
public static ImageLoader getImageLoader(Context ctx){
if(imageLoader == null){
if(imageQueue == null){
imageQueue = Volley.newRequestQueue(ctx.getApplicationContext());
}
imageLoader = new ImageLoader(imageQueue, new ImageLoader.ImageCache() {
Map<String, Bitmap> cache = new HashMap<String, Bitmap>();
@Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
return imageLoader;
}
}
文件 user_view_dialog.xml
将以下内容添加到您的布局XML文件中以添加图像:
<com.android.volley.toolbox.NetworkImageView
android:id="@+id/profile_picture"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
app:srcCompat="@android:drawable/spinner_background"/>
文件 UserViewDialog.java
将以下代码添加到onCreate方法(Fragment,Activity)或构造函数(Dialog)中:
NetworkImageView profilePicture = view.findViewById(R.id.profile_picture)
profilePicture.setImageUrl("http://example.com/users/images/profile.jpg", ImageFetch.getImageLoader(getContext())
Picasso
Picasso是来自Square的另一个优秀库。请查看网站以获取一些很棒的示例。