Android Learning note Volley (vi) Implementation gets the string response of the server ...

Source: Internet
Author: User

Learning content:

1. Get the string response of the server using the Stringrequest implementation ...

The first few have been on the service-response process of the source code analysis, the entire process, then volley in the end to achieve what is the request we need to use in the development ... Volley implementation is not a lot of things, its main function is to implement the asynchronous network request and image loading, in fact, asynchronous loading parse JSON data, asynchronously get the server's string data, asynchronous implementation of network image dynamic loading, there is a request is to empty the cache request, But the use of the place is not a lot, mainly in front of the three aspects, so volley relative to andbase, in fact, is a lightweight framework, and andbase involved in something more extensive, comprehensive, but the network request this part of the use of volley basically is enough ...

1.stringrequest.java

 PackageCom.android.volley.toolbox;ImportCom.android.volley.NetworkResponse;Importcom.android.volley.Request;ImportCom.android.volley.Response;ImportCom.android.volley.Response.ErrorListener;ImportCom.android.volley.Response.Listener;Importjava.io.UnsupportedEncodingException; Public classStringrequestextendsRequest<string> {    Private FinalListener<string> Mlistener;//Request a successful listener ...//creates a Stringrquest object based on the specified request method and URL ...     PublicStringrequest (intmethod, String URL, listener<string>Listener, Errorlistener Errorlistener) {        Super(method, URL, errorlistener);//set the request method, URL, and error listener :Mlistener = listener;//set Successful listener ...    }    //creates a Stringrequest object based on the specified URL, with the default request method of Get:     PublicStringrequest (String URL, listener<string>Listener, Errorlistener Errorlistener) {         This(method.get, URL, Listener, errorlistener); }    //This involves the process of sending a response ... Indicates that the response of the entire request has been returned ...@Overrideprotected voidDeliverresponse (String response) {mlistener.onresponse (response); }    //The parsing process for the response ...@OverrideprotectedResponse<string>Parsenetworkresponse (networkresponse response) {String parsed; Try{parsed=NewString (Response.data, Httpheaderparser.parsecharset (response.headers));//encapsulating the response data, parsing the character set ...}Catch(Unsupportedencodingexception e) {parsed=NewString (Response.data); }        returnResponse.success (parsed, httpheaderparser.parsecacheheaders (Response));//return request succeeded ...    }}

Above is just stringrequest the source code implementation, very simple ... So let's take a concrete look at how to use ...

Generally used in a simple response to return some basic data information, such as user login, when sending a POST request to send the user's account information and password, the server needs to call the database for the relevant search ... The response needs to be returned to the server after the response is completed, usually in the form of a string ...

 PackageCom.example.oop;ImportCom.android.volley.RequestQueue;ImportCom.android.volley.toolbox.ImageLoader;ImportCom.android.volley.toolbox.ImageLoader.ImageCache;ImportCom.android.volley.toolbox.NetworkImageView;ImportCom.android.volley.toolbox.Volley;ImportAndroid.os.Bundle;Importandroid.app.Activity;ImportAndroid.graphics.Bitmap;ImportAndroid.support.v4.util.LruCache;ImportAndroid.view.Menu;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener; Public classMainactivityextendsActivityImplementsOnclicklistener {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main);    Init (); }     Public voidinit () {requestqueue queue=volley.newrequestqueue (mainactivity. This);//Create a request queue first ...//then you need to add the related request to the request queue ...Queue.add (NewStringrequest ("http://www.baidu.com/",NewListener <StringRequest>(){        //request succeeded, receive override of Request method ...@Override Public voidOnresponse (String response) {System.out.println (response.tostring ()); }    },NewErrorlistener () {//request failed, get to error ...@Override Public voidonerrorresponse (volleyerror error) {System.out.println (error.tostring ());          }    }); } @Override Public BooleanOncreateoptionsmenu (Menu menu) {//inflate the menu; This adds items to the action bar if it is present.getmenuinflater (). Inflate (R.menu.main, menu); return true; }}  

Here we want to send the Baidu page related requests, then no doubt, the request is inevitable, then the return of something is the original data Baidu page, in fact, is the HTML page code ... Then we cannot parse this page, but the browser is possible, we can load this page through the browser ... This is just a simple little example, the purpose is that we need to know what data the server is returning to us ...

A second example:

This is an intermediate JSP method for process processing ... To process the account and password, just a simple way, we can also go through it to connect the database, perfect this function ... Here is just a simple little example ...

 <% String name  =request.getparameter (" name "  );  String password  =request.getparameter ("password" );  if  ("Darker". Equals (name) && "49681888" .equals (password))    {out.println ( Receive name is: "+name); OUT.PRINTLN ( Receive password is: "+password);%> Your Message was right  ! <%}else  {out.println ( "Receive name    is: "+name); OUT.PRINTLN ( Receive password is: "+password);%> Your Message was wrong  ! <%}%> 

then the activity needs to send the request parameter through the POST request, only then can pass this function to carry on the next judgment ... Because there are no methods to pass parameters in the POST request ... But we can do this by overriding the GetParam () method ... To specify the relevant parameters, the server automatically calls the parameters in GetParam () ....

 PackageCom.example.oop;//Some of the packages are not referenced and are automatically referenced at the time of writing ...ImportCom.android.volley.RequestQueue;ImportCom.android.volley.toolbox.Volley;ImportAndroid.os.Bundle;Importandroid.app.Activity;ImportAndroid.view.Menu;ImportAndroid.view.View; Public classMainactivityextendsActivity {TextView TV; String URL= "192.168.19.172:8080/jsp/post.jsp"@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); TV=(TextView) Findviewbyid (r.id.tv_1);    Init (); }     Public voidinit () {requestqueue queue=volley.newrequestqueue (mainactivity. This);//Create a request queue first ...Queue.add (NewStringrequest (method.post, URL,NewListener<string>() {@Override Public voidOnresponse (String response) {//TODO auto-generated Method StubSystem.out.println (response.tostring ()); Tv.settext (Response.tostring ()); //to display the data obtained ...    }}, NewErrorlistener () {@Override Public voidonerrorresponse (volleyerror error) {//TODO auto-generated Method StubSystem.out.println (error.tostring ()); }}){      //in this method to complete the relevant transfer of parameters ....@OverrideprotectedMap<string, String>getparams ()throwsauthfailureerror{Map<string, string>map=NewHashmap<string, string>(); Map.put ("Name", "darker"); Map.put ("Password", "49681888"); returnmap;        }});} @Override Public BooleanOncreateoptionsmenu (Menu menu) {//inflate the menu; This adds items to the action bar if it is present.getmenuinflater (). Inflate (R.menu.main, menu); return true; }}

Using the POST request to complete the verification, there is no doubt that the client will get to receive name Is:darker,receive password Is:49681888,your because we passed the parameters correctly. Message is right! this piece of information ...

Stringrequest request is very simple, the things involved are not many, suitable for sending network requests to obtain the corresponding string data, presented to the client ...

Android Learning note Volley (vi) Implementation gets the string response of the server ...

Related Article

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.