Retrofit是Square针对Android网络I/O设计的一套框架。Square官方介绍Retrofit:“A type-safe HTTP client for Android and Java”。Retrofit 2底层基于OkHttp实现,OkHttp依然是Square针对网络请求设计的一整套解决方案。Retrofit是基于Okhttp的一套RESTful http网络请求框架封装。
给出一个Retrofit网络加载简例,该简例实现一个简单的功能,从一个网络链接地址下载一张图片设置到ImageView里面。注意链接的拼接和注解使用。
上层Java代码:
package zhangphil.http;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.GET;
import retrofit2.http.Path;
public class MainActivity extends AppCompatActivity {
private Call<ResponseBody> mCall;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView imageView = (ImageView) findViewById(R.id.image);
Retrofit mRetrofit = new Retrofit.Builder()
.baseUrl("https:///")
.build();
MyRetrofitService mRetrofitService = mRetrofit.create(MyRetrofitService.class);
mCall = mRetrofitService.getImagesByName("bd_logo1.png");
Log.d("请求的网络链接", String.valueOf(mCall.request().url()));
mCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
byte[] bytes = response.body().bytes();
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
imageView.setImageBitmap(bmp);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
mCall.cancel();
}
private interface MyRetrofitService {
@GET("img/{picName}")
Call<ResponseBody> getImagesByName(@Path("picName") String picName);
}
}
不要忘记网络权限:
<uses-permission android:name="android.permission.INTERNET"/>