今天介绍一个知道的人不多的库,写个简单的页面什么的。用起来很爽?如果你疑惑那么多开源的网络库为啥不用?
因为这个简单方便。拿来就用。经过这几天的实践。确实可以。推荐一下
如果你需要 GITHUB
首先。引入依赖
implementation 'com.amitshekhar.android:android-networking:1.0.2'
添加权限:
<uses-permission android:name="android.permission.INTERNET" />
然后你可以选择在app的onCreate种注册,当然。也可以在Application里
AndroidNetworking.initialize(getApplicationContext());
然后就是正题了:
通过一些自定义对其进行初始化,因为它使用OkHttp作为网络层,您可以在初始化时传递自定义 okHttpClient。
// Adding an Network Interceptor for Debugging purpose :
OkHttpClient okHttpClient = new OkHttpClient() .newBuilder().addNetworkInterceptor(new StethoInterceptor()).build();
AndroidNetworking.initialize(getApplicationContext(),okHttpClient);
使用带有 Jackson Parser 的快速 Android 网络
implementation 'com.amitshekhar.android:jackson-android-networking:1.0.2'
// Then set the JacksonParserFactory like below
AndroidNetworking.setParserFactory(new JacksonParserFactory());
如果你要使用GET请求
AndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}").addPathParameter("pageNumber", "0").addQueryParameter("limit", "3").addHeaders("token", "1234").setTag("test").setPriority(Priority.LOW).build().getAsJSONArray(new JSONArrayRequestListener() {@Overridepublic void onResponse(JSONArray response) {// do anything with response}@Overridepublic void onError(ANError error) {// handle error}});
如果你要使用POST请求
AndroidNetworking.post("https://fierce-cove-29863.herokuapp.com/createAnUser").addBodyParameter("firstname", "Amit").addBodyParameter("lastname", "Shekhar").setTag("test").setPriority(Priority.MEDIUM).build().getAsJSONObject(new JSONObjectRequestListener() {@Overridepublic void onResponse(JSONObject response) {// do anything with response}@Overridepublic void onError(ANError error) {// handle error}});
您还可以像这样在 POST 请求中发布 java 对象、json、文件等。
User user = new User();
user.firstname = "Amit";
user.lastname = "Shekhar";AndroidNetworking.post("https://fierce-cove-29863.herokuapp.com/createUser").addBodyParameter(user) // posting java object.setTag("test").setPriority(Priority.MEDIUM).build().getAsJSONArray(new JSONArrayRequestListener() { public void onResponse(JSONArray response) {// do anything with response} public void onError(ANError error) {// handle error}});JSONObject jsonObject = new JSONObject();
try {jsonObject.put("firstname", "Amit");jsonObject.put("lastname", "Shekhar");
} catch (JSONException e) {e.printStackTrace();
}AndroidNetworking.post("https://fierce-cove-29863.herokuapp.com/createUser").addJSONObjectBody(jsonObject) // posting json.setTag("test").setPriority(Priority.MEDIUM).build().getAsJSONArray(new JSONArrayRequestListener() { public void onResponse(JSONArray response) {// do anything with response} public void onError(ANError error) {// handle error}});AndroidNetworking.post("https://fierce-cove-29863.herokuapp.com/postFile").addFileBody(file) // posting any type of file.setTag("test").setPriority(Priority.MEDIUM).build().getAsJSONObject(new JSONObjectRequestListener() { public void onResponse(JSONObject response) {// do anything with response} public void onError(ANError error) {// handle error}});
将它与您自己的 JAVA 对象一起使用 - JSON Parser
/*--------------Example One -> Getting the userList----------------*/
AndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}").addPathParameter("pageNumber", "0").addQueryParameter("limit", "3").setTag(this).setPriority(Priority.LOW).build().getAsObjectList(User.class, new ParsedRequestListener<List<User>>() {@Overridepublic void onResponse(List<User> users) {// do anything with responseLog.d(TAG, "userList size : " + users.size());for (User user : users) {Log.d(TAG, "id : " + user.id);Log.d(TAG, "firstname : " + user.firstname);Log.d(TAG, "lastname : " + user.lastname);}}@Overridepublic void onError(ANError anError) {// handle error}});
/*--------------Example Two -> Getting an user----------------*/
AndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAnUserDetail/{userId}").addPathParameter("userId", "1").setTag(this).setPriority(Priority.LOW).build().getAsObject(User.class, new ParsedRequestListener<User>() {@Overridepublic void onResponse(User user) {// do anything with responseLog.d(TAG, "id : " + user.id);Log.d(TAG, "firstname : " + user.firstname);Log.d(TAG, "lastname : " + user.lastname);}@Overridepublic void onError(ANError anError) {// handle error}});
/*-- Note : YourObject.class, getAsObject and getAsObjectList are important here --*/
从服务器下载文件
AndroidNetworking.download(url,dirPath,fileName).setTag("downloadTest").setPriority(Priority.MEDIUM).build().setDownloadProgressListener(new DownloadProgressListener() {@Overridepublic void onProgress(long bytesDownloaded, long totalBytes) {// do anything with progress }}).startDownload(new DownloadListener() {@Overridepublic void onDownloadComplete() {// do anything after completion}@Overridepublic void onError(ANError error) {// handle error }});
上传文件
AndroidNetworking.upload(url).addMultipartFile("image",file) .addMultipartParameter("key","value").setTag("uploadTest").setPriority(Priority.HIGH).build().setUploadProgressListener(new UploadProgressListener() {@Overridepublic void onProgress(long bytesUploaded, long totalBytes) {// do anything with progress }}).getAsJSONObject(new JSONObjectRequestListener() {@Overridepublic void onResponse(JSONObject response) {// do anything with response }@Overridepublic void onError(ANError error) {// handle error }});
在另一个线程执行器中获取响应和完成
(注意:错误和进度将始终在应用程序的主线程中返回)
AndroidNetworking.upload(url).addMultipartFile("image",file) .addMultipartParameter("key","value") .setTag("uploadTest").setPriority(Priority.HIGH).build().setExecutor(Executors.newSingleThreadExecutor()) // setting an executor to get response or completion on that executor thread.setUploadProgressListener(new UploadProgressListener() {@Overridepublic void onProgress(long bytesUploaded, long totalBytes) {// do anything with progress }}).getAsJSONObject(new JSONObjectRequestListener() {@Overridepublic void onResponse(JSONObject response) {// below code will be executed in the executor provided// do anything with response }@Overridepublic void onError(ANError error) {// handle error }});
如果请求已完成给定阈值,则设置不取消请求的百分比阈值
AndroidNetworking.download(url,dirPath,fileName).setTag("downloadTest").setPriority(Priority.MEDIUM).setPercentageThresholdForCancelling(50) // even if at the time of cancelling it will not cancel if 50% .build() // downloading is done.But can be cancalled with forceCancel..setDownloadProgressListener(new DownloadProgressListener() {@Overridepublic void onProgress(long bytesDownloaded, long totalBytes) {// do anything with progress }}).startDownload(new DownloadListener() {@Overridepublic void onDownloadComplete() {// do anything after completion}@Overridepublic void onError(ANError error) {// handle error }});
取消请求。
AndroidNetworking.cancel("tag"); // All the requests with the given tag will be cancelled.
AndroidNetworking.forceCancel("tag"); // All the requests with the given tag will be cancelled , even if any percent threshold is// set , it will be cancelled forcefully.
AndroidNetworking.cancelAll(); // All the requests will be cancelled.
AndroidNetworking.forceCancelAll(); // All the requests will be cancelled , even if any percent threshold is// set , it will be cancelled forcefully.
从网络加载图像到 ImageView
<com.androidnetworking.widget.ANImageViewandroid:id="@+id/imageView"android:layout_width="100dp"android:layout_height="100dp"android:layout_gravity="center" />imageView.setDefaultImageResId(R.drawable.default);imageView.setErrorImageResId(R.drawable.error);imageView.setImageUrl(imageUrl);
使用某些指定参数从 url 获取位图
AndroidNetworking.get(imageUrl).setTag("imageRequestTag").setPriority(Priority.MEDIUM).setBitmapMaxHeight(100).setBitmapMaxWidth(100).setBitmapConfig(Bitmap.Config.ARGB_8888).build().getAsBitmap(new BitmapRequestListener() {@Overridepublic void onResponse(Bitmap bitmap) {// do anything with bitmap}@Overridepublic void onError(ANError error) {// handle error}});
为特定请求自定义 OkHttpClient
OkHttpClient okHttpClient = new OkHttpClient().newBuilder().addInterceptor(new GzipRequestInterceptor()).build();AndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}").addPathParameter("pageNumber", "0").addQueryParameter("limit", "3").addHeaders("token", "1234").setTag("test").setPriority(Priority.LOW).setOkHttpClient(okHttpClient) // passing a custom okHttpClient .build().getAsJSONArray(new JSONArrayRequestListener() {@Overridepublic void onResponse(JSONArray response) {// do anything with response}@Overridepublic void onError(ANError error) {// handle error}});
想更多了解。自己去看吧