RestHttp
项目地址:
RestHttp
简介:Android 基于 HttpURLConnection 简单易用的网络库,支持 Http,Https,Http 文件上传,图片加载,面向接口的 API 调用方式,轻量的设计风格,Android 初学者的学习教程
- RestHttp 提供了三级缓存(服务器缓存,内存缓存,硬盘缓存),通过动态代理的方式实现了面向接口调用 API。
- 封装了 HttpURLConnection,简单易用的 API 设计。
- Debug 模式下设置日志 TAG,所有网络请求日志输出,方便调试。
gradle 依赖
compile 'cn.alien95:resthttp:1.0.5'
使用方法
- 初始化:设置日志 TAG
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
RestHttp.initialize(this);
Utils.initialize(this);
RestHttp.setDiskCacheSize(100 * 1024 * 1024);
if (BuildConfig.DEBUG) {
Utils.setDebug(true,"Debug");
RestHttp.setDebug(true, "network");
}
}
}
通过接口定义 API
- API 接口类
public interface ServiceAPI {
//同步请求方式:不能包含 Callback 参数
@POST("/v1/users/login.php")
UserInfo loginPostSync(@Field("name")
String name,
@Field("password")
String password);
//异步请求:必须有一个 Callback 参数作为回调
@POST("/v1/users/login.php")
void loginAsyn(@Field("name")
String name,
@Field("password")
String password, RestCallback<UserInfo> restCallback);
//GET 请求同步
@GET("/v1/users/login_get.php")
UserInfo loginGetSync(@Query("name")
String name,
@Query("password")
String password);
//GET 请求异步
@GET("/213-4")
void getMusicData(@Query("topid") int topId,
@Query("showapi_appid") String showapiAppId,
@Query("showapi_sign") String secretKey,
RestCallback<String> callback);
}
Java 类方式请求数据
- Http --- GET,POST
public void get(){
mResult.setText("");
HttpRequest.getInstance().get(GET_URL, new HttpCallback() {
@Override
public void success(String info) {
mResult.setText(new Gson().toJson(info));
}
});
}
public void post(){
mResult.setText("");
Map<String,String> params = new HashMap<>();
params.put("page","1");
HttpRequest.getInstance().addHeader("UID","1");
HttpRequest.getInstance().addHeader("token","9ba712a6210728364ea7c2d7457cde");
HttpRequest.getInstance().post(POST_URL, params,new HttpCallback() {
@Override
public void success(String info) {
mResult.setText(new Gson().toJson(info));
}
});
}
-
Http 文件上传
HttpFile.getInstance().uploadFile(UPLOAD_URL, null, "picture", mImageFile, new HttpCallback() { @Override public void success(String info) { Utils.Toast(info + " : http://115.29.107.20/image/test_upload.jpg"); } }
-
Https
HttpsRequest.getInstance().get("https://baidu.com/", new HttpsCallback() { @Override public void success(String info) { mResult.setText(info); } });
图片加载 --- 支持大图压缩
- HttpImageView
<cn.alien95.resthttp.view.HttpImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:adjustViewBounds="true" />
imageView.setImageUrl(imageUrl);
- 可以指定压缩比例或固定的宽和高
image.setInSimpleSize(inSimpleSize);
image.setImageUrlWithCompress(IMAGE_SMALL_URL, 800, 600);
注意事项
- 依赖的其他库
compile 'com.jakewharton:disklrucache:2.0.2'
compile 'com.google.code.gson:gson:2.6.2'