Android implementation gets the string response of the server

Source: Internet
Author: User
Tags character set stub

Learning content:

Example One, using the stringrequest implementation to get the string response of the server ...

 ,
What exactly are the requests that are implemented in Android volley that we need to use in development ... Volley realize things are not many, its main function is to implement asynchronous network request and picture loading, in fact, is asynchronous load parsing JSON data, asynchronous access to the server's string data, asynchronous implementation of the network picture dynamic loading, there is a request to empty the cache request, However, the use of the place is not a lot, mainly in front of three aspects, so volley relative to andbase, in fact, is still a lightweight framework, and andbase involved in the more extensive, comprehensive, but the network request this part of the use of volley basic is enough ...

1.stringrequest.java


package com.android.volley.toolbox;
import com.android.volley.networkresponse;
import com.android.volley.request;
import com.android.volley.response;
import com.android.volley.response.errorlistener;
import com.android.volley.response.listener;
import java.io.unsupportedencodingexception; public class stringrequest extends request<string> {     private final listener<string> mlistener; //Request Successful listening ...     // Creates a Stringrquest object based on the specified request method and URL ...     public stringrequest (int method,  String url, listener<string> listener,              errorlistener errorlistener)  {       
 super (Method, url, errorlistener);  //set request method, URL, and error monitor.         mlistener = listener; //set to monitor successfully ...    &nbsp}     //
Creates a Stringrequest object based on the specified URL, and the request method defaults to get.     public stringrequest (String url, listener<string> listener,  errorlistener errorlistener)  {        this (Method.GET,
 url, listener, errorlistener); &NBSP;&NBSP;&NBSP;&NBSP}     //Here is the process of sending a response ... Indicates that the response of the entire request has returned ...      @Override     protected void  Deliverresponse (string response)  {        
Mlistener.onresponse (response); &NBSP;&NBSP;&NBSP;&NBSP}     //The resolution process for the response ...      @Override      protected response<string> parsenetworkresponse (NetworkResponse response)  {        String parsed;          try {             parsed = new string (Response.data, httpheaderparser.parsecharset (response.headers));  //for response data encapsulation, parsing character set ...         } catch  ( Unsupportedencodingexception e)  {           
 parsed = new string (Response.data);         }         return  Response.success (Parsed, httpheaderparser.parsecacheheaders (Response))//Return request succeeded ...     &NBSP}}

The



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

  Generally use in a simple response, return some basic data information, such as user login, send a POST request to send the user's account information and password, the server needs to fetch the database for related search ... After completing this response, you need to return the response information for the server, which is usually sent as a string ...


package com.example.oop;
import com.android.volley.requestqueue;
import com.android.volley.toolbox.imageloader;
import com.android.volley.toolbox.imageloader.imagecache;
import com.android.volley.toolbox.networkimageview;
import com.android.volley.toolbox.volley;
import android.os.bundle;
import android.app.activity;
import android.graphics.bitmap;
import android.support.v4.util.lrucache;
import android.view.menu;
import android.view.view;
import android.view.view.onclicklistener;
public class mainactivity extends activity implements onclicklistener {      @Override     protected void oncreate (bundle 
savedinstancestate)  {        super.oncreate (savedInstanceState);
        setcontentview (R.layout.activity_main);       &nbSp; init (); &NBSP;&NBSP;&NBSP;&NBSP}     public void init () {     
   requestqueue queue=volley.newrequestqueue (mainactivity.this);  //first create a request queue ...  //Then you need to add related requests to the request queue ...   Queue.add (new stringrequest) ("http://www.baidu.com/", new listener& Nbsp;   <stringrequest> () {        //request succeeded, Override of Receive Request method ...          @Override          public void onresponse (string response) {       
     system.out.println (Response.tostring ()); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP}     },new errorlistener () { // Request failed, access to error ...          @Override          public void onerrorResponse (volleyerror error) {            
System.out.println (Error.tostring ()); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP}    &nbsp});            }           @Override      public boolean oncreateoptionsmenu (menu menu)  {         // inflate the menu; this adds items to the action
 bar if it is present.
        getmenuinflater (). Inflate (R.menu.main, menu);
        return true; &NBSP;&NBSP;&NBSP;&NBSP}}




  Here we would like Baidu page to send the relevant request, then there is no doubt that the request is inevitable, then the return of things is Baidu page of the original data, is actually HTML page code ... Then we can't parse this page, but the browser is OK, we can load this page through the browser ... This is just a simple little example, the purpose is that we need to be clear, the server returned to us is what data ...

  Second example:

  This is a JSP method for process processing in the middle ... For processing accounts and passwords, just a simple way, of course, we can also through it to connect the database, perfect this function ... Here is just a simple 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 are right!
<%}else{
out.println ("Receive name is:" +name);
Out.println ("Receive password is:" +password);%>
Your message are wrong!
<%}%>




Then the activity needs to send the request parameter through the POST request, only then can carry on the next judgment by this function ... Because there is no way to pass parameters in post requests ... But we can rewrite the GetParam () method ... To specify the relevant parameters, the server will automatically invoke the parameters in GetParam () ....


package com.example.oop;
Some of the packages are not referenced and are automatically referenced when they are written ... import com.android.volley.requestqueue;
import com.android.volley.toolbox.volley;
import android.os.bundle;
import android.app.activity;
import android.view.menu;
import android.view.view; public class mainactivity extends activity {      textview
 tv;
    string url= "192.168.19.172:8080/jsp/post.jsp"      @Override     protected void oncreate (bundle savedinstancestate)  {  
      super.oncreate (savedinstancestate);
        setcontentview (R.layout.activity_main);
        tv= (TextView) Findviewbyid (r.id.tv_1);
        init (); &NBSP;&NBSP;&NBSP;&NBSP}     public void init () {&nbsP;       requestqueue queue=volley.newrequestqueue (MainActivity.this);  //first create a request queue ...     queue.add (new stringrequest method.post, url, new  Listener<string> ()  {          @Override      public void onresponse (string response)  {         // todo auto-generated method stub         
System.out.println (Response.tostring ());         tv.settext (Response.tostring ());  //display of the data obtained ...   &NBSP;&NBSP;&NBSP}}, new errorlistener ()  {     @Override      public void onerrorresponse (volleyerror error)  {         // todo auto-generated method stub &NBSP;&NBSp;        system.out.println (Error.tostring ());                 &nbsp}}) {       //in this method to complete the correlation transfer of parameters ....      @Override     protected map <string, string>getparams ()  throws authfailureerror{      
  Map<String, String>map=new HashMap<String, String> ();
        map.put ("name",  "darker");
        map.put ("Password",  "49681888");
        return map;
    }}); }           @Override     public boolean  Oncreateoptionsmenu (menu menu)  {        // inFlate the menu; this adds items to the action bar if it
 is present.
        getmenuinflater (). Inflate (R.menu.main, menu);
        return true; &NBSP;&NBSP;&NBSP;&NBSP}}




  Use post requests to complete validation, and there is no doubt that this is true because of the arguments we pass, so the client obtains the receive name Is:darker,receive password is : 49681888,your message are right! this piece of information ... The

  Stringrequest request is very simple and does not involve many things, and is suitable for sending a network request to obtain the appropriate string data and presenting it to the client

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.