Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> android網絡請求庫volley方法詳解,androidvolley

android網絡請求庫volley方法詳解,androidvolley

編輯:關於android開發

android網絡請求庫volley方法詳解,androidvolley


使用volley進行網絡請求:需先將volley包導入androidstudio中

File下的Project Structrue,點加號導包

 

 

volley網絡請求步驟:

      1. 創建請求隊列       RequestQueue queue = Volley.newRequestQueue(this);

      2.創建請求對象(3種)     

                       StringRequest request = new StringRequest(“請求方法”,“請求的網絡地址”,“成功的網絡回調”,“失敗的網絡回調”);

                       ImageRequest request = new ImageRequest(“圖片路徑”,“成功的回調函數”,“圖片寬度”,“圖片高度”,“圖片的顏色屬性”,“失敗的網絡回調”);

                       Jsonrequest request = new Jsonrequest();

      3.把請求對象放入請求隊列     queue.add(request);

  注銷請求:重寫onstop方法

   @Override
protected void onStop() {
super.onStop();
/*取消當前請求隊列的所有請求*/
queue.cancelAll(this);
/*取消當前請求隊列tag為get的請求*/
queue.cancelAll("get");
/*取消當前請求隊列tag為post的請求*/
queue.cancelAll("post");
}
設置當前請求的優先級:重寫getPriority方法
@Override
public Priority getPriority() {
return Priority.LOW;
}
設置請求頭:重寫GetHeader方法
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> map = new HashMap<String, String>();
map.put("apikey","fc642e216cd19906f642ee930ce28174");
return map;
}

傳遞參數:重寫GetParams方法
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> map = new HashMap<String, String>();
map.put("num","10");
map.put("page","1");
map.put("word","%E6%9E%97%E4%B8%B9");
return map;
}

代碼部分:
xml文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.jredu.helloworld.activity.VolleyActivity">
    <WebView
        android:id="@+id/volleyWebView"
        android:layout_width="match_parent"
        android:layout_height="300dp">
    </WebView>
    <ImageView
        android:id="@+id/img"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/volleyButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:textAllCaps="false"
        android:text="Volley"/>
    <Button
        android:id="@+id/imgButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:textAllCaps="false"
        android:text="Volley獲取圖片"/>
</LinearLayout>

  activity文件:

package com.jredu.helloworld.activity;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
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.HttpHeaderParser;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.jredu.helloworld.R;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

public class VolleyActivity extends AppCompatActivity {
    WebView webView;
    Button button;
    Button imgButton;
    ImageView img;
    RequestQueue queue = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_volley);
        queue = Volley.newRequestQueue(this);
        webView = (WebView) findViewById(R.id.volleyWebView);
        img = (ImageView) findViewById(R.id.img);
        button = (Button) findViewById(R.id.volleyButton);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doStringVolley2();
                doStringVolley();
            }
        });
        imgButton = (Button) findViewById(R.id.imgButton);
        imgButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GetImg();
            }
        });
    }
    /*get方法*/
    public void doStringVolley(){
        /*創建請求隊列*/
        //RequestQueue queue = Volley.newRequestQueue(this);
        /*創建請求對象*/
        StringRequest request = new StringRequest(
                Request.Method.GET,
                "http://apis.baidu.com/txapi/tiyu/tiyu?num=10&page=1&word=%E6%9E%97%E4%B8%B9",
                /*"http://www.baidu.com",*/
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        String s = response;
                        webView.getSettings().setDefaultTextEncodingName("utf-8");
                        webView.getSettings().setJavaScriptEnabled(true);
                        webView.loadDataWithBaseURL(null,s,"text/html","utf-8",null);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        webView.loadDataWithBaseURL(null,"網絡連接失敗!!!","text/html","utf-8",null);
                    }
                }
        ){
            /*設置請求頭*/
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String,String> map = new HashMap<String, String>();
                map.put("apikey","fc642e216cd19906f642ee930ce28174");
                return map;
            }
            /*解析網絡請求結果的方法*/
            @Override
            protected Response<String> parseNetworkResponse(
                    NetworkResponse response) {
                try {
                    String jsonObject = new String(
                            new String(response.data, "UTF-8"));
                    return        Response.success(jsonObject, HttpHeaderParser.parseCacheHeaders(response));
                } catch (UnsupportedEncodingException e) {
                    return Response.error(new ParseError(e));
                } catch (Exception je) {
                    return Response.error(new ParseError(je));
                }
            }
            /*設置當前請求的優先級*/
            @Override
            public Priority getPriority() {
                return Priority.LOW;
            }
        };
        request.setTag("get");
        /*把請求對象放入請求隊列*/
        queue.add(request);
    }
    /*post方法*/
    public void doStringVolley2(){
        /*創建請求隊列*/
        //RequestQueue queue = Volley.newRequestQueue(this);
        /*創建請求對象*/
        StringRequest request = new StringRequest(
                Request.Method.POST,
                "http://www.baidu.com",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        String s = response;
                        webView.getSettings().setDefaultTextEncodingName("utf-8");
                        webView.getSettings().setJavaScriptEnabled(true);
                        webView.loadDataWithBaseURL(null,s,"text/html","utf-8",null);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        webView.loadDataWithBaseURL(null,"網絡連接失敗!!!","text/html","utf-8",null);
                    }
                }
        ){
            /*重寫params方法寫參數*/
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<String, String>();
                map.put("num","10");
                map.put("page","1");
                map.put("word","%E6%9E%97%E4%B8%B9");
                return map;
            }
            /*設置請求對象優先級*/
            @Override
            public Priority getPriority() {
                return Priority.HIGH;
            }
        };
        request.setTag("post");
        /*把請求對象放入請求隊列*/
        queue.add(request);
    }
    /*獲取圖片*/
    public void GetImg(){
        ImageRequest request = new ImageRequest(
                "https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png",
                new Response.Listener<Bitmap>() {
                    @Override
                    public void onResponse(Bitmap response) {
                        img.setImageBitmap(response);
                    }
                },
                5000,
                5000,
                Bitmap.Config.ARGB_8888,
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        img.setImageResource(R.drawable.first5);
                    }
                }
        );
        queue.add(request);
    }
    /*重寫onStop方法,用來注銷請求*/
    @Override
    protected void onStop() {
        super.onStop();
        /*取消當前請求隊列的所有請求*/
        queue.cancelAll(this);
        /*取消當前請求隊列tag為get的請求*/
        queue.cancelAll("get");
        /*取消當前請求隊列tag為post的請求*/
        queue.cancelAll("post");
    }
}

 









  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved