Today brings you the first Android network communication framework,Volley request
- Volley is introduced
- Will do the operation
- StringRequest Indicates a text request
- JsonObjectRequest gets JSON string GET and POST requests
-
- A GET request
- A POST request
- ImageRequest sets the image
- ImageLolder
Volley is introduced
Volley introduced a new network communication framework at Google I/O conference in 2013. Its design goal is to be very suitable for network operations with small amount of data but frequent communication. For network operations with large amount of data, such as downloading files, Volley’s performance is very poor.
Will do the operation
Add the dependent
Implementation ‘com. Android. Volley: volley: 1.1.1’
As you all know, INTERNET permissions must be added to all network requests.
The < USES – permission android: name = “android. Permission. INTERNET” / >
Android10 and above also need to add add plaintext permissions:
In the androidmanifest.xml application:
Android: usesCleartextTraffic = “true”
StringRequest Indicates a text request
- You need to get the RequestQueue object first
- Then we get the StringRequest object
- Then set the StringRequest object in using the RequestQueue object.add() method
/**
* Creates a new GET request.
*
* @param url URL to fetch the string at
* @param listener Listener to receive the String response
* @param errorListener Error listener, or null to ignore errors
*/
public StringRequest(String url, Listener<String> listener, @Nullable ErrorListener errorListener)
Copy the code
/ / RequestQueue object
RequestQueue queue = Volley.newRequestQueue(this);
// Get the StringRequest object // Here the URL is not easy to reveal, but you can see the result
StringRequest stringRequest = new StringRequest(STRINGREQUEST_URL, new Response.Listener<String>() {
@Override// Return correctly
public void onResponse(String response) {
Log.i("StringRequestResponse",response);
} // Error return
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i("onErrorResponse",error.getMessage()); }});// Set the RequestQueue object with the add() method
queue.add(stringRequest);
Copy the code
Note :StringRequest() is only recommended to request text information
Kangkang Log returns the result:
JsonObjectRequest gets JSON string GET and POST requests
- You need to get the RequestQueue object first
- Then get the JsonObjectRequest object
- Then set the JsonObjectRequest object in using the RequestQueue object.add() method
/**
* Creates a new request.
*
* @param method the HTTP method to use
* @param url URL to fetch the JSON from
* @param jsonRequest A {@link JSONObject} to post with the request. Null indicates no
* parameters will be posted along with request.
* @param listener Listener to receive the JSON response
* @param errorListener Error listener, or null to ignore errors.
*/
public JsonObjectRequest(
int method,
String url,
@Nullable JSONObject jsonRequest,
Listener<JSONObject> listener,
@Nullable ErrorListener errorListener)
Copy the code
A GET request
// Get the RequestQueue object
RequestQueue queue = Volley.newRequestQueue(this);
// Get the JsonObjectRequest object
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest("http://www.weather.com.cn/data/city3jdata/china.html".null.new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.i("JsonObjectResponse", response.toString()); }},new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i("JsonObjectResponse", error.getMessage()); }});// Use the RequestQueue object.add () method to set the JsonObjectRequest object
queue.add(jsonObjectRequest);
Copy the code
Come to Kangkang Log:
As you can see, the JSONObject is returned, and you still need to go through native JSONObject parsing to get the desired result, so this method is not recommended for requesting network data. Retrofit or OkHttp is recommended, etc
A POST request
I don’t want to repeat it,
Here are some things to note:
- The first argument to JsonObjectRequest() must be request.method.post.
- The PARAMETERS of the POST request are set by JSONObject()
Map params = new HashMap();
params.put("app_key"."74D2E724FE2B69EF7EA3F38E9400CF71");
// Create a native JSONObject and set the map to it
JSONObject jsonObject = new JSONObject(params);
/** * Parameter 1 :POST declaration * Parameter 2: request POST path * Parameter 3 :JSONObject Set the key and value of POST * Parameter 4: Return JSONObject on success * Parameter 5: return error */
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,url, jsonObject , new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.i("JsonObjectResponse", response.toString()); }},new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i("JsonObjectonResponse", response.toString()); }}); queue.add(jsonObjectRequest);Copy the code
If the request code is 200, the request is successful:
As I expected, the return code was indeed 200;
ImageRequest sets the image
/**
* Creates a new image request, decoding to a maximum specified width and height. If both width
* and height are zero, the image will be decoded to its natural size. If one of the two is
* nonzero, that dimension will be clamped and the other one will be set to preserve the image's
* aspect ratio. If both width and height are nonzero, the image will be decoded to be fit in
* the rectangle of dimensions width x height while keeping its aspect ratio.
*
* @param url URL of the image
* @param listener Listener to receive the decoded bitmap
* @param maxWidth Maximum width to decode this bitmap to, or zero for none
* @param maxHeight Maximum height to decode this bitmap to, or zero for none
* @param scaleType The ImageViews ScaleType used to calculate the needed image size.
* @param decodeConfig Format to decode the bitmap to
* @param errorListener Error listener, or null to ignore errors
*/
public ImageRequest(
String url,
Response.Listener<Bitmap> listener,
int maxWidth,
int maxHeight,
Config decodeConfig,
Response.ErrorListener errorListener)
Copy the code
Usage has been basically, here is not detailed, to have parameters do not understand, you can see the source notes!
// Get the RequestQueue object
RequestQueue queue = Volley.newRequestQueue(this);
// Get the ImageRequest object
/** The fifth parameter is used to specify the color properties of the image. Several constants under bitmap. Config can be used here, with ARGB_8888 showing the best color properties and 4 bytes per image pixel and RGB_565 showing 2 bytes per image pixel */
ImageRequest imageRequest = new ImageRequest("http://api.map.baidu.com/images/weather/day/zhenyu.png".new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap response) {
// Set the bitmap image
Log.i("ImageRequestResponse"."1111"); mImage.setImageBitmap(response); }},0.0, Bitmap.Config.ARGB_8888, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i("onErrorResponse111",error.getMessage()+""); }}); queue.add(imageRequest);Copy the code
You can see that the image is set successfully!
ImageLolder
ImageLoader can be used to load images from the web, and it uses ImageRequest internally. However, ImageLoader is obviously more efficient than ImageRequest because it not only helps us cache images, but also filters out duplicate links. Avoid sending requests repeatedly;
- Create a RequestQueue object.
- Create an ImageLoader object.
- Gets an ImageListener object.
- Call the get() method of ImageLoader to load images from the network.
/ / RequestQueue object.
RequestQueue requestQueue = Volley.newRequestQueue(this);
/** * ImageCache() object */
ImageLoader imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
@Override //
public Bitmap getBitmap(String url) {
Log.i("ImageLoadergetBitmap",url+"");
return null;
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
// Set the image to image2
image2.setImageBitmap(bitmap);
Log.i("ImageLoaderputBitmap",url+"\t\t"+bitmap); }});/** * Parameter 1: ImageView object to set * Parameter 2: display default image during image loading * parameter 3: display failed image loading */
// Set the image to image
ImageLoader.ImageListener imageListener = ImageLoader.getImageListener(mImage, R.drawable.ic_launcher_foreground, R.drawable.ic_launcher_background);
/ * * * parameters: photo interface * parameter 2: ImageLoader. ImageListener object * three parameters: maximum width * four parameters: maximum height * /
imageLoader.get("http://api.map.baidu.com/images/weather/night/duoyun.png",imageListener,200.200);
Copy the code
Set the image to iAMGE and Image2 at the same time to create the Kangkang effect:
Very simple to use, but more repeated code, looking very ugly, next article (click to see). Write a tool class for you to use in the future:
Git link: Langyangyang.
Welcome to point out the inadequacies! Let us know in the comments