Android框架Volley使用:Post請求實現


首先我們在項目中導入這個框架:

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

在AndroidManifest文件當中添加網絡權限:

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

下面是我們的首頁布局:
在這個布局當中我們將Volley框架的所有功能都做成了一個按鈕,按下按鈕之后就會在“顯示結果”下面顯示結果,顯示結果下面使用了一個ScrollView,並在ScrollView下面嵌套了一個Textview和Imageview,用於把我們加載成功之后的圖片和文字進行顯示。

下面是首頁布局的代碼:

復制代碼
<?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請求"/>
    <Button
        android:id="@+id/post"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Post請求"/>
    <Button
        android:id="@+id/json"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="請求JSON"/>
    <Button
        android:id="@+id/ImageRquest"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="ImageRquest加載圖片"/>
    <Button
        android:id="@+id/ImageLoader"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="ImageLoader加載圖片"/>
    <Button
        android:id="@+id/NetWorkImageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="NetWorkImageView加載圖片"/>
    <TextView
        android:text="顯示結果"
        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>
復制代碼

為了實現POST請求,進行POST請求一共需要三步,分別是:

  1. 創建一個請求隊列
  2. 創建一個請求
  3. 將創建的請求添加到請求隊列當中

在創建請求的時候,必須同時寫兩個監聽器,一個是實現請求,正確接受數據的回調,另一個是發生異常之后的回調。這里我們准備了json數據,是在gank.io的官網上找的,大家可以自行百度一下,這里就直接采用了網址:

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

當中的json數據進行POST請求了,只要我們在文本顯示區返回的數據和這個網站上面的數據顯示相同,則請求成功。如果不同也會顯示出錯誤的原因。

實現的核心代碼如下:

 post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 1 創建一個請求隊列
                RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);

                // 2 創建一個post請求
                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("請求失敗" + volleyError);
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {

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

                        return map;
                    }
                };

                // 3 將post請求添加到隊列中
                requestQueue.add(stringRequest);




            }
        });

全部主活動的Java代碼如下:

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()//把需要初始化的控件的邏輯都寫在這里是一個很好的編程范式
    {

        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) {
                //創建一個請求隊列
                RequestQueue requestQueue=Volley.newRequestQueue(MainActivity.this);
                //創建一個請求
                String url="http://gank.io/api/xiandu/category/wow";
                StringRequest stringRequest=new StringRequest(url, new Response.Listener<String>() {
                   //正確接受數據之后的回調
                    @Override
                    public void onResponse(String response) {
                    tv_volley_result.setText(response);
                    }
                }, new Response.ErrorListener() {//發生異常之后的監聽回調
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        tv_volley_result.setText("加載錯誤"+error);
                    }
                });
                //將創建的請求添加到請求隊列當中
                requestQueue.add(stringRequest);
            }
        });


        post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 1 創建一個請求隊列
                RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);

                // 2 創建一個post請求
                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("請求失敗" + volleyError);
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {

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

                        return map;
                    }
                };

                // 3 將post請求添加到隊列中
                requestQueue.add(stringRequest);




            }
        });

        json.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
// 1 創建一個請求隊列
                RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);

                // 2 創建一個請求
                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("請求失敗" + volleyError);
                    }
                });

                // 3 將創建的請求添加到請求隊列中
                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) {

            }
        });

    }
}

 





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM