Code For Better 谷歌开发者之声——Android 中的 Volley 库

Volley是一个HTTP 库,它使 Android 应用程序的网络变得非常简单和快速。它由 Google 开发并在 2013 年 Google I/O 期间推出。它的开发是因为 Android SDK 中缺少能够在不影响用户体验的情况下工作的网络类。尽管 Volley 是 Android 开源项目 (AOSP) 的一部分,但 Google 在 2017 年 1 月宣布 Volley 将迁移到一个独立的库。它管理网络请求的处理和缓存,并节省开发人员一次又一次编写相同的网络调用/缓存代码的宝贵时间。Volley不适合大型下载或流式操作,因为 Volley 在解析期间将所有响应保存在内存中。

Volley 的特点

1.请求排队和优先级
2.有效的请求缓存和内存管理
3.库的可扩展性和定制化以满足我们的需求
4.取消请求

使用 Volley 的优势

1.所有需要在 Android 中使用 Networking 完成的任务,都可以在 Volley 的帮助下完成。
2.网络请求的自动调度。
3.捕捉。
4.多个并发网络连接。
5.取消请求 API。
6.请求优先级。
7.Volley 提供调试和跟踪工具。

如何导入 Volley 并添加权限

在开始使用 Volley 之前,需要在 Android 项目中导入 Volley 并添加权限。这样做的步骤如下:

创建一个新项目。打开build.gradle(Module: app)并添加以下依赖项:

dependencies{
    
     
    //...
    implementation 'com.android.volley:volley:1.0.0'
}

AndroidManifest.xml添加互联网权限:

<uses-permission android:name="android.permission.INTERNET" />

Volley Library 中的类别

Volley 有两个主要类别:

1.请求队列:将请求分发到网络时使用的兴趣。如果需要,可以根据需要创建一个请求队列,但通常它是在启动时的早期创建的,并保留它并将其用作 Singleton。
2.请求:进行 Web API 调用的所有必要信息都存储在其中。它是创建网络请求(GET、POST)的基础。

使用 Volley 库的请求类型

字符串请求

String url = "https:// string_url/";
StringRequest
	stringRequest
	= new StringRequest(
		Request.Method.GET,
		url,
		new Response.Listener() {
    
    
			@Override
			public void onResponse(String response)
			{
    
    
			}
		},
		new Response.ErrorListener() {
    
    
			@Override
			public void onErrorResponse(VolleyError error)
			{
    
    
			}
		});
requestQueue.add(stringRequest);
</pre>

JSON对象请求

String url = "https:// json_url/";
JsonObjectRequest
	jsonObjectRequest
	= new JsonObjectRequest(
		Request.Method.GET,
		url,
		null,
		new Response.Listener() {
    
    
			@Override
			public void onResponse(JSONObject response)
			{
    
    
			}
		},
		new Response.ErrorListener() {
    
    
			@Override
			public void onErrorResponse(VolleyError error)
			{
    
    
			}
		});
requestQueue.add(jsonObjectRequest);

JSONArray 请求

JsonArrayRequest
	jsonArrayRequest
	= new JsonArrayRequest(
		Request.Method.GET,
		url,
		null,
		new Response.Listener() {
    
    
			@Override
			public void onResponse(JSONArray response)
			{
    
    
			}
		},
		new Response.ErrorListener() {
    
    
			@Override
			public void onErrorResponse(VolleyError error)
			{
    
    
			}
		});
requestQueue.add(jsonArrayRequest);

图片请求

int max - width = ...;
int max_height = ...;

String URL = "http:// image_url.png";

ImageRequest
	imageRequest
	= new ImageRequest(URL,
					new Response.Listener() {
    
    
						@Override
						public void
						onResponse(Bitmap response)
						{
    
    
							// Assign the response
							// to an ImageView
							ImageView
								imageView
								= (ImageView)
									findViewById(
										R.id.imageView);

							imageView.setImageBitmap(response);
						}
					},
					max_width, max_height, null);

requestQueue.add(imageRequest);

添加帖子参数

String tag_json_obj = "json_obj_req";

String
	url
	= "https:// api.xyz.info/volley/person_object.json";

ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...PLease wait");
pDialog.show();

JsonObjectRequest
	jsonObjReq
	= new JsonObjectRequest(
		Method.POST,
		url,
		null,
		new Response.Listener() {
    
    

			@Override
			public void onResponse(JSONObject response)
			{
    
    
				Log.d(TAG, response.toString());
				pDialog.hide();
			}
		},
		new Response.ErrorListener() {
    
    

			@Override
			public void onErrorResponse(VolleyError error)
			{
    
    
				VolleyLog.d(TAG, "Error: "
									+ error.getMessage());
				pDialog.hide();
			}
		}) {
    
    

		@Override
		protected Map getParams()
		{
    
    
			Map params = new HashMap();
			params.put("name", "Androidhive");
			params.put("email", "[email protected]");
			params.put("password", "password123");

			return params;
		}

	};

AppController.getInstance()
	.addToRequestQueue(jsonObjReq, tag_json_obj);

添加请求标头

String tag_json_obj = "json_obj_req";

String
	url
	= "https:// api.androidhive.info/volley/person_object.json";

ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();

JsonObjectRequest
	jsonObjReq
	= new JsonObjectRequest(
		Method.POST,
		url,
		null,
		new Response.Listener() {
    
    

			@Override
			public void onResponse(JSONObject response)
			{
    
    
				Log.d(TAG, response.toString());
				pDialog.hide();
			}
		},
		new Response.ErrorListener() {
    
    

			@Override
			public void onErrorResponse(VolleyError error)
			{
    
    
				VolleyLog.d(TAG, "Error: "
									+ error.getMessage());
				pDialog.hide();
			}
		}) {
    
    

		@Override
		public Map getHeaders() throws AuthFailureError
		{
    
    
			HashMap headers = new HashMap();
			headers.put("Content-Type", "application/json");
			headers.put("apiKey", "xxxxxxxxxxxxxxx");
			return headers;
		}

	};

AppController.getInstance()
	.addToRequestQueue(jsonObjReq, tag_json_obj);

处理 Volley 缓存

// 从缓存加载请求
Cache
	cache
	= AppController.getInstance()
		.getRequestQueue()
		.getCache();

Entry entry = cache.get(url);
if (entry != null) {
    
    
	try {
    
    
		String
			data
			= new String(entry.data, "UTF-8");
		// 处理数据,例如将其转换为 xml、json、位图等,
	}
	catch (UnsupportedEncodingException e) {
    
    
		e.printStackTrace();
	}
}
}
else
{
    
    
	// 如果缓存的响应不存在
}

// 使缓存无效
AppController.getInstance()
	.getRequestQueue()
	.getCache()
	.invalidate(url, true);

// 关闭缓存字符串请求
StringRequest
	stringReq
	= new StringRequest(....);

// 禁用缓存
stringReq.setShouldCache(false);

// 删除特定缓存的缓存</strong>
AppController.getInstance()
	.getRequestQueue()
	.getCache()
	.remove(url);

// 删除所有缓存
AppController.getInstance()
	.getRequestQueue()
	.getCache()
	.clear(url);

取消请求

// 取消单个请求
String tag_json_arry = "json_req";

ApplicationController.getInstance()
	.getRequestQueue()
	.cancelAll("feed_request");

// 取消所有请求
ApplicationController.getInstance()
	.getRequestQueue()
	.cancelAll();

请求优先级

private Priority priority = Priority.HIGH;

StringRequest
	strReq
	= new StringRequest(
		Method.GET,
		Const.URL_STRING_REQ,
		new Response
			.Listener() {
    
    

					@Override
					public void onResponse(String response) {
    
    

						Log.d(TAG, response.toString());
						msgResponse.setText(response.toString());
						hideProgressDialog();

					} },
		new Response
			.ErrorListener() {
    
    

					@Override
					public void
					onErrorResponse(VolleyError error) {
    
    

						VolleyLog.d(TAG,
									"Error: "
										+ error.getMessage());
						hideProgressDialog();
					} }) {
    
    

		@Override
		public Priority getPriority()
		{
    
    
			return priority;
		}

	};

猜你喜欢

转载自blog.csdn.net/qq_53544522/article/details/126774617