Android framework Volley basic use: Post request implementation

Keywords: Android JSON network Java

First, we import this framework into the project:

implementation 'com.mcxiaoke.volley:library:1.0.19'

Add network permissions to the Android Manifest file:

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

Here is our homepage layout:
In this layout, we make all the functions of the Volley Framework into a button. When we press the button, the result will be displayed under the "Display Results". A ScrollView is used under the display results, and a Textview and Imageview are nested under the ScrollView to display the pictures and text after loading successfully.

The following is the code for the home page layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
<Button
    android:id="@+id/get"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Get request"/>
    <Button
        android:id="@+id/post"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Post request"/>
    <Button
        android:id="@+id/json"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text= "Request JSON"/>
    <Button
        android:id="@+id/ImageRquest"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        Android: text = "Image Rquest Load Picture" />
    <Button
        android:id="@+id/ImageLoader"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        Android: text = "Image Loader Loader Load Pictures" />
    <Button
        android:id="@+id/NetWorkImageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        Android: text = "NetWork Image View Load Pictures" />
    <TextView
        android:text = "display results"
        android:textSize="20sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <ImageView
        android:visibility="gone"
        android:id="@+id/iv_volley"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <com.android.volley.toolbox.NetworkImageView
        android:id="@+id/NetWork"
        android:visibility="gone"
        android:layout_width="200dp"
        android:layout_height="200dp" />
   <ScrollView
       android:layout_width="match_parent"
       android:layout_height="match_parent">
       <TextView
           android:id="@+id/tv_volley_result"
           android:layout_width="match_parent"
           android:layout_height="match_parent" />



   </ScrollView>
</LinearLayout>

In order to implement POST requests, three steps are needed to make POST requests, namely:

  1. Create a request queue
  2. Create a request
  3. Add the created request to the request queue

When creating a request, two listeners must be written at the same time. One is to implement the request, correctly accept the callback of data, and the other is to call back after an exception occurs. Here we have prepared the json data, which was found on gank.io's official website. You can Baidu by yourself. Here we use the website directly:

http://api.m.mtime.cn/PageSubArea/TrailerList.api

The json data in it is POST requests, as long as the data we return in the text display area is the same as the data displayed on the website, the request succeeds. If it is different, it will show the cause of the error.

The core code of the implementation is as follows:

 post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 1 Create a request queue
                RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);

                // 2 Create a post request
                String url = "http://api.m.mtime.cn/PageSubArea/TrailerList.api";
                StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        tv_volley_result.setText(s);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        tv_volley_result.setText("request was aborted" + volleyError);
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {

                        Map<String, String> map = new HashMap<String, String>();
//                        map.put("value1","param1");

                        return map;
                    }
                };

                // 3 take post Request added to queue
                requestQueue.add(stringRequest);




            }
        });

The Java code for all the main activities is as follows:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    private Button get;
    private Button post;
    private Button json;
    private Button imagerequest;
    private  Button imageload;
    private  Button netWorkImageView;

    private ImageView iv;
    private NetworkImageView network;
    private TextView tv_volley_result;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initview();
        initListener();

    }
    public void initview()//It's a good programming paradigm to write all the logic of the controls that need to be initialized here.
    {

        get=findViewById(R.id.get);
        post=findViewById(R.id.post);
        json=findViewById(R.id.json);
        imagerequest=findViewById(R.id.ImageRquest);
        imageload=findViewById(R.id.ImageLoader);
        netWorkImageView=findViewById(R.id.NetWorkImageView);
        iv=findViewById(R.id.iv_volley);
        network=findViewById(R.id.NetWork);
        tv_volley_result=findViewById(R.id.tv_volley_result);



    }
    public void initListener()
    {
        get.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Create a request queue
                RequestQueue requestQueue=Volley.newRequestQueue(MainActivity.this);
                //Create a request
                String url="http://gank.io/api/xiandu/category/wow";
                StringRequest stringRequest=new StringRequest(url, new Response.Listener<String>() {
                   //Callback after correct acceptance of data
                    @Override
                    public void onResponse(String response) {
                    tv_volley_result.setText(response);
                    }
                }, new Response.ErrorListener() {//Monitoring callback after an exception occurs
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        tv_volley_result.setText("Loading error"+error);
                    }
                });
                //Add the created request to the request queue
                requestQueue.add(stringRequest);
            }
        });


        post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 1 Create a request queue
                RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);

                // 2 Create a post request
                String url = "http://api.m.mtime.cn/PageSubArea/TrailerList.api";
                StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        tv_volley_result.setText(s);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        tv_volley_result.setText("request was aborted" + volleyError);
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {

                        Map<String, String> map = new HashMap<String, String>();
//                        map.put("value1","param1");

                        return map;
                    }
                };

                // 3 take post Request added to queue
                requestQueue.add(stringRequest);




            }
        });

        json.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
// 1 Create a request queue
                RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);

                // 2 Create a request
                String url = "http://gank.io/api/xiandu/category/wow";
                JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        tv_volley_result.setText(jsonObject.toString());
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        tv_volley_result.setText("request was aborted" + volleyError);
                    }
                });

                // 3 Add the created request to the request queue
                requestQueue.add(jsonObjectRequest);



            }
        });

        imagerequest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });


        imageload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });

        netWorkImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });

    }
}

 




Posted by donny1298 on Sun, 19 May 2019 06:11:19 -0700