欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

android 网络请求库volley方法详解

程序员文章站 2024-03-05 08:33:42
使用volley进行网络请求:需先将volley包导入androidstudio中 file下的project structrue,点加号导包   voll...

使用volley进行网络请求:需先将volley包导入androidstudio中

file下的project structrue,点加号导包

 android 网络请求库volley方法详解

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");
 }
}

以上就是android 网络请求库volley方法 的资料整理,后续继续补充相关资料,谢谢大家对本站的支持!