Android Network Request library Volley method detailed _android

Source: Internet
Author: User

Using volley to make network requests: you need to first import volley packages into Androidstudio

Project Structrue under File, point Plus Guide package

Volley Network Request steps:

1. Create request queue Requestqueue queue = Volley.newrequestqueue (this);

2. Create Request object (3 kinds)

Stringrequest request = new Stringrequest ("Request Method", "Requested network address", "Successful network callback", "Failed network callback");

Imagerequest request = new Imagerequest ("Picture Path", "Successful callback function", "Picture width", "Picture height", "Picture color attribute", "Failed network callback");

Jsonrequest request = new Jsonrequest ();

3. Put the request object into the request queue Queue.add (requests);

 Logoff request: Overriding the OnStop method

 @Override
  protected void OnStop () {
   super.onstop ();
   /* Cancel all requests for the current request
   /Queue.cancelall (this);
   /* Cancel current request queue tag for Get/*
   Queue.cancelall ("get");
   /* Cancel current request queue tag for post
   /Queue.cancelall ("post");
  }
Sets the priority of the current request: Overriding the GetPriority method
@Override public
Priority getpriority () {return
 priority.low;
}
Set Request headers: Override the GetHeader method
@Override public
map<string, string> getheaders () throws Authfailureerror {
 map<string,string> Map = new hashmap<string, string> ();
 Map.put ("Apikey", "fc642e216cd19906f642ee930ce28174");
 return map;
}

Passing parameters: Overriding the Getparams method
@Override
protected map<string, string> Getparams () throws Authfailureerror {
 map<string,string> Map = new hashmap<string, string> ();
 Map.put ("num", "ten");
 Map.put ("page", "1");
 Map.put ("word", "%e6%9e%97%e4%b8%b9");
 return map;
}

Code section:

XML file:

<?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=" WR Ap_content "/> <button android:id= @+id/volleybutton" android:layout_width= "Match_parent" Android:layout_heig ht= "Wrap_content" android:layout_margintop= "5DP" android:textaLlcaps= "false" android:text= "Volley"/> <button android:id= "@+id/imgbutton" android:layout_width= "Match_paren" T "android:layout_height=" wrap_content "android:layout_margintop=" 5DP "android:textallcaps=" false "android:text=" V
 Olley get Pictures "/> </LinearLayout>

  Activity files:

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; Requestqueuequeue = 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 method/public void Dostringvolley () {/* Create request queue *///requestqueue queue = Volley.newrequestqueue (this); /* Create Request Object/* 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) {Web
     View.loaddatawithbaseurl (NULL, "Network connection Failed!!!", "text/html", "Utf-8", null); {/* Set request Header/* @Override public map<string, String> getheaders () throws Authfailureerror {map& Lt
    string,string> map = new hashmap<string, string> ();
    Map.put ("Apikey", "fc642e216cd19906f642ee930ce28174");
   return map;  }/* Methods to resolve network request Results * * * @Override protected response<string> parsenetworkresponse (Networkresponse Response) {try {String jsonobject = 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));
   }/* Set the priority of the current request/* @Override public Priority getpriority () {return priority.low;
  }
  };
  Request.settag ("get");
 /* Put the request object into the request queue/Queue.add (requests);
  /*post method/public void DoStringVolley2 () {/* Create request queue *///requestqueue queue = Volley.newrequestqueue (this); /* Create Request Object/* Stringrequest request = new Stringrequest (Request.Method.POST, "http://www.baidu.com", New RESPO Nse.
      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) {Web
     View.loaddatawithbaseurl (NULL, "Network connection Failed!!!", "text/html", "Utf-8", null); }} {/* override params Method Write parameter/* * @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;
   /* Set Request Object Priority * * @Override public Priority getpriority () {return priority.high;
  }
  };
  Request.settag ("post");
 /* Put the request object into the request queue/Queue.add (requests); */* Get picture/public void getimg () {imagerequest request = new Imagerequest ("Https://ss0.bdstatic.com/5aV1bjqh_Q23od  Cf/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 V
     OID Onerrorresponse (volleyerror error) {Img.setimageresource (R.DRAWABLE.FIRST5);
  }
    }
  );
 Queue.add (Request);
  /* Rewrite the OnStop method to unregister the request/@Override protected void OnStop () {super.onstop ();
  /* Cancel all requests for the current request/queue.cancelall (this);
  /* Cancel current request queue tag for Get/* Queue.cancelall ("get");
 /* Cancel current request queue tag for POST request * * * Queue.cancelall ("post");

 }
}

Above is the Android Network request library volley method of data collation, follow-up to continue to supplement the relevant information, thank you for your support for this site!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.