Android uses Google's recommended networking framework volley to make it easier to connect to a network

Source: Internet
Author: User

hello everyone, with the progress of technology, science and technology developed, few applications are single-machine, most of them need to network access to the server, we used to
HttpClient and HttpURLConnection, feeling is not very troublesome, and Google especially for developers to consider, launched the volley, from this mother no longer worry about my networking problem, where the link does not connect where, volley make networking easier and faster, and volley request will be executed asynchronously, does not block the main thread network request is nothing more than get or post, we rarely use the delete this request way, said so much nonsense, let us see what volley can do. Is it really so magical, open sesame, let's explore volley together! One: Volley provides the function

1, encapsulated the asynchronous restful request API;

2, an elegant and robust request queue;

3, an extensible architecture, it enables developers to implement a custom request and response processing mechanism;

4, can use the external HTTP client library;

5, cache policy;

6, custom network image load view (networkimageview,imageloader, etc.);

Two: why asynchronous HTTP requests are used? Android requires an HTTP request to execute asynchronously, and an android.os.NetworkOnMainThreadException exception may be thrown if an HTTP request is executed on the main thread. Blocking the main thread has some serious consequences, it hinders UI rendering, the user experience is not fluent, and it can lead to scary ANR (application not responding). To avoid these traps, as a developer, you should always make sure that the HTTP request is on a different thread. Three: The Get and post methods of the body volleyfirst we want to use volley to import Volley.jar into our project,
so we can make it, let's take a look at Get and post code, as follows:
Package Com.zqy.myvolley;import Java.util.hashmap;import Java.util.map;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.request.method;import Com.android.volley.response.errorlistener;import Com.android.volley.response.listener;import Com.android.volley.toolbox.stringrequest;import Com.android.volley.toolbox.volley;import Android.os.Bundle; Import Android.text.textutils;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.toast;import Android.app.activity;public class MainActivity extends Activity implements Onclicklistener {private Requestqueue mqueue; String url= "http://www.baidu.com"; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (R.layout.activity_main); Mqueue=volley.newrequestqueue (this); <spaN style= "Color:rgb (51, 51, 51); Font-family: Song body; font-size:14px; line-height:28px; " > Create a Requestqueue object. </span>initview ();} private void Initview () {Final button btnget= (button) Findviewbyid (r.id.btn_get); final button btnpost= (button) Findviewbyid (R.id.btn_post); Btnget.setonclicklistener (this); Btnpost.setonclicklistener (this);} @Overridepublic void OnClick (View v) {switch (V.getid ()) {case r.id.btn_get:initget (); Break;case r.id.btn_post: Initpost (); break;default:break;}} private void Initget () {//get request Method is Getmqueue.add (new Stringrequest (Method.get,url, New listener<string> () {@ overridepublic void Onresponse (String arg0) {toast.maketext (mainactivity.this, "Get Request succeeded", 2). Show ();//success, write code to process content here }}, new Errorlistener () {@Overridepublic void Onerrorresponse (Volleyerror arg0) {toast.maketext (Mainactivity.this, " Get request Failed ", 2). Show ();//Failed})); private void Initpost () {//post request//This writes your own internal class postresquest .... Method changed to Postmqueue.add (New Postresquest (Method.post,url, New Listener<strinG> () {@Overridepublic void Onresponse (String arg0) {toast.maketext (Mainactivity.this, "POST request succeeded", 2). Show ();//Success, Write the code here to process the content}}, new Errorlistener () {@Overridepublic void Onerrorresponse (Volleyerror arg0) {Toast.maketext ( Mainactivity.this, "POST request Failed", 2). Show ();//Failed}));} Write an internal class, post inside put some server required parameters class Postresquest extends Stringrequest {public postresquest (int method, String Url,listener <String> Listener, Errorlistener Errorlistener) {Super (method, URL, listener, errorlistener);} Protected Map<string, string> Getparams () throws Authfailureerror {map<string, string> params = new HASHMAP&L T String, string> ();p arams.put ("Name", "small Source");//Parameter Params.put ("Age", 22+ "");//parameter return params;}}}
This is the network of code, is not particularly simple, thanhttpclient and HttpURLConnection are much simpler, and they are executed asynchronously, without the need for handler at all. Let us develop more convenient, simpler, more efficient, let's look at the layout of the XML, inside I put two button, a execute Get method, one executes the post method. As follows:
<relativelayout 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 "    tools:context= ". Mainactivity ">    <button        android:id=" @+id/btn_get "        android:layout_width=" Wrap_content        " android:layout_height= "Wrap_content"        android:layout_alignparenttop= "true"        android:layout_ Centerhorizontal= "true"        android:layout_margintop= "28DP"        android:text= "Get Request"/>    <button        android:id= "@+id/btn_post"        android:layout_width= "wrap_content"        android:layout_height= "Wrap_ Content "        android:layout_alignleft=" @+id/btn_get "        android:layout_below=" @+id/btn_get "        android: layout_margintop= "47DP"        android:text= "POST request"/></relativelayout>
OK. It's not easy to finish, isn't it?httpclient and HttpURLConnection say goodbye with volley say hello that. Finally wish the Android system better, let us Android win Blades walk in the world of technology, yeah~~~~let's see, with volley propaganda picture! Go go, go home, it's going to rain outside! By the way, almost forgot, do not have to add Internet access. You can't get an error!
<uses-permission android:name= "Android.permission.INTERNET" >


Gee, post How to request failed, on the phone is successful, my parameters are blind spell! Just do a negative failure of the case, really help me also ah! It's gone! It's raining!

Source Download





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.